How To Reverse A Singly Linked List In Java Without Recursion ... - Java67

Pages

  • Home
  • core java
  • spring
  • online courses
  • thread
  • java 8
  • coding
  • sql
  • books
  • oop
  • interview
  • certification
  • free resources
  • best
How to reverse a singly linked list in Java without recursion? Iterative Solution Example Hello guys, reverse a linked list is a common coding problem from Programming Job interviews and I am sure you have seen this in your career, if you are not, maybe you are a fresher and you will going to find about this very soon in your next technical interview. In the last article, I have shown you how to use recursion to reverse a linked list, and today, I'll show you how to reverse a singly linked list in Java without recursion. A singly linked list, also known as just linked list is a collection of nodes that can only be traversed in one direction like in the forward direction from head to tail. Each node in the linked list contains two things, data and a pointer to the next node in the list. In order to reverse the linked list, you need to iterate through the list, and at each step, we need to reverse the link like after the first iteration head will point to null and the next element will point to the head. At the end of traversal when you reach the tail of the linked list, the tail will point to the second last element and it will become a new head because you can now traverse through all elements from this node. Since we cannot use the java.util.LinkedList class to demonstrate this example, as it is a doubly-linked list and also in most of the time on coding interviews, the Interviewer will not allow you to use existing Java classes or API. Anyway, in a doubly-linked list, you can traverse in both directions like both forward and backward as each node contains the reference to both the previous and next node. Btw, if you are not familiar with the linked list data structure, it's better to first go through a good data structure and algorithm course like Data Structures and Algorithms: Deep Dive Using Java to learn more about linked lists data structure.

Implementing Your Own Linked List on Interviews

Since using existing Java classes is now allowed on Programming Job interviews, you need to create your own to write code. For this example, I have created our own singly linked list class. Similar to java.util.LinkedList also contains a nested static class Node, which represents a node in the linked list. This class contains an integer attribute to hold the data part and another Node reference to point to the next one in the list. If you want to create a Generic linked list, you should replace int withT, a generic type, as shown here. In order to demonstrate that our reverse method is working, we will not only have to create a linked list but also need to populate the linked list. In order to populate, you need to implement the add() method on the singly linked list. You have two choices, either add the element at the head or at the tail, adding an element to the head is easy as it doesn't require a traversal till the end but if you want to create a list that contains elements in the order they are added then we need to add nodes at the end of the linked list. I have also created a print() method to print all nodes of the singly linked list, separated by space. This method is very useful to demonstrate that our reverse method is actually working or not, as you can print the linked list before and after reversal. If you struggle with implementing essential data structures like a linked list, binary tree, the hash table in your own code on any programming language like Java then I suggest you join Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight. They will not only help you to write your data structure but also how to calculate time and space complexity. How to Reverse a Singly linked list without Recursion in Java? Coding Problem with Solution

Java Program to Reverse a singly linked list without Recursion

Here is our sample program to demonstrate how to reverse a linked list in Java. In order to reverse, I have first created a class called SinglyLinkedList, which represents a linked list data structure. I have further implemented add() and print() method to add elements to the linked list and print them in forwarding order. The logic of reversing the linked list is encapsulated inside the reverse() method. It traverses through the linked list from head to tail and reverses the link in each step like each node instead of pointing to the next element started pointing to the previous node, this way the whole linked list is reversed when you reach the last element, which then becomes the new head of a linked list. Here is a nice diagram that explains the algorithm to reverse a linked list without recursion in Java: You can see that links are reversed in each step using the pointer's previous and next. This is also known as the iterative algorithm to reverse the linked list in Java. For the recursive algorithm, you can also see Introduction to Algorithms book by Thomas H. Cormen. package test; /** * Java Program to reverse a singly list without using recursion. */ public class LinkedListProblem { public static void main(String[] args) { // creating a singly linked list SinglyLinkedList.Node head = new SinglyLinkedList.Node(1); SinglyLinkedList linkedlist = new SinglyLinkedList(head); // adding node into singly linked list linkedlist.add(new SinglyLinkedList.Node(2)); linkedlist.add(new SinglyLinkedList.Node(3)); // printing a singly linked list linkedlist.print(); // reversing the singly linked list linkedlist.reverse(); // printing the singly linked list again linkedlist.print(); } } /** * A class to represent singly list in Java * * @author WINDOWS 8 * */ class SinglyLinkedList { static class Node { private int data; private Node next; public Node(int data) { this.data = data; } public int data() { return data; } public Node next() { return next; } } private Node head; public SinglyLinkedList(Node head) { this.head = head; } /** * Java method to add an element to linked list * @param node */ public void add(Node node) { Node current = head; while (current != null) { if (current.next == null) { current.next = node; break; } current = current.next; } } /** * Java method to print a singly linked list */ public void print() { Node node = head; while (node != null) { System.out.print(node.data() + " "); node = node.next(); } System.out.println(""); } /** * Java method to reverse a linked list without recursion */ public void reverse() { Node pointer = head; Node previous = null, current = null; while (pointer != null) { current = pointer; pointer = pointer.next; // reverse the link current.next = previous; previous = current; head = current; } } } Output 1 2 3 3 2 1 You can see that the linked list has reversed, earlier 1 was the first element now it is last and 3 is the first element of the linked list or head. That's all about how to reverse a singly linked list in Java without using recursion. Yes, we have not used recursion in this solution, instead, we have used iteration. You can see the while loop inside the reverse() method. Btw, if you get this question asked in the real interview, you would be most likely asked to reverse the linked list using recursion now. So, wait for another article to see that solution or check out the Cracking the Coding Interview book, which contains a solution to this problem along with several others. Related Data Structure and Algorithm Interview Questions from Javarevisited Blog
  • How to find the middle element of the linked list using a single pass? (solution)
  • 10 Free courses to learn Data Structure and Algorithms (courses)
  • How to find the 3rd element from the end of a linked list in Java? (solution)
  • 7 Free Books to learn Data Structure and Algorithms (books)
  • Top 15 Data Structure and Algorithm Interview Questions (see here)
  • Top 20 String coding interview questions (see here)
  • When to use ArrayList vs LinkedList in Java? (answer)
  • 20+ linked list interview questions for programmers (questions)
  • How to find if a singly linked list contains a loop? (solution)
  • 7 Best Courses to learn Data Structure for Beginners (best courses)
  • How to find the first and last element of a linked list in Java? (solution)
  • How to convert a linked list to an array in Java? (example)
  • How to search elements inside a linked list in Java? (solution)
  • What is the difference between LinkedList and ArrayList in Java? (answer)
  • Top 30 Array Coding Interview Questions with Answers (see here)
  • Top 30 linked list coding interview questions (see here)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • 50+ Data Structure and Algorithms Problems from Interviews (questions)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome. P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free data structure and algorithms courses on Udemy.

2 comments:

  1. TrOubleshootersMarch 2, 2021 at 5:50 PM

    while (pointer != null) { current = pointer; pointer = pointer.next; // reverse the link current.next = previous; previous = current; head = current; } }Read more: https://www.java67.com/2016/07/how-to-reverse-singly-linked-list-in-java-example.html#ixzz6o0evpeNX

    ReplyDeleteReplies
      Reply
  2. Tales to TravelDecember 21, 2021 at 4:06 PM

    I found that using https://youtube.com/playlist?list=PL1MJrDFRFiKZg-4Th9SO7ev4SP8AUd3a7 and follow through this playlist will really give me a good understanding about LinkedList Reversal

    ReplyDeleteReplies
      Reply
Add commentLoad more...

Feel free to comment, ask questions if you have any doubt.

Newer Post Older Post Home Subscribe to: Post Comments (Atom)

Recommended Courses

  • best python courses
  • best java courses
  • system design courses
  • best spring courses
  • best hibernate courses
  • best design pattern courses
  • best Linux courses
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses

Categories

  • .NET
  • abstract class
  • Affiliate marketing
  • After Effects
  • Agile
  • AI Tools
  • Amazon Web Service
  • android
  • Angular
  • Anonymous class
  • Ansible
  • apache camel
  • Apache kafka
  • Apache spark
  • app development
  • array
  • ArrayList
  • Artificial Intelligence
  • automation
  • aws
  • aws certification
  • Azure Certifications
  • backend development
  • bash
  • basics
  • beginners
  • best of java67
  • best practices
  • Big Data
  • binary tree
  • bit manipulation
  • black friday deals
  • Blockchain
  • BlockingDeque
  • books
  • Bootstrap
  • business analysis
  • ByteByteGo
  • C programming
  • C++
  • Career
  • ChatGPT
  • Chef
  • cloud certification
  • Cloud Computing
  • Code Example
  • Code Review
  • codecademy
  • Codemia
  • CodeRabbit
  • coding
  • coding exercise
  • Coding Interview
  • Coding Problems
  • Comparator
  • computer science
  • Computer Vision
  • concurrency tutorial
  • ConcurrentHashMap
  • core java
  • core java interview question answer
  • course review
  • Coursera
  • courses
  • crontab
  • CSS
  • Cyber Monday
  • Cyber Security
  • Data Analysis
  • data science
  • data structure and algorithm
  • Data Visualization
  • database
  • datacamp
  • date and time
  • debugging
  • deep learning
  • default methods
  • design pattern
  • DevOps
  • DevSecOps
  • Distributed Systems
  • Django
  • docker
  • double
  • Drawing
  • dyanmic programming
  • dynamic Programming
  • eBooks
  • Eclipse
  • EJB
  • enum
  • equals
  • error and exception
  • Ethical hacking
  • Excel
  • exception
  • Exponent
  • expressjs
  • FAANG
  • Figma
  • Firebase
  • flatmap
  • float
  • Flutter
  • free resources
  • freelancing
  • Frontend Masters
  • fun
  • Fundamental
  • fundamentals
  • Game development
  • garbage collection
  • general
  • Generics
  • gifts
  • git and github
  • golang
  • Google Cloud Certification
  • Google Cloud Platform
  • Gradle
  • grails
  • graph
  • graphic design
  • grep
  • Groovy
  • gRPC
  • Hadoop
  • HashMap
  • HashSet
  • haskell
  • Hibernate
  • Hibernate interview Question
  • homework
  • HTML
  • HTTP
  • HttpClient
  • i
  • interface
  • Internet of Things (IoT)
  • interview
  • interview questions
  • IT Certification
  • J2EE
  • Jackson
  • java
  • Java 5 tutorial
  • java 7
  • Java 8
  • java 9
  • java basics
  • Java Certification
  • Java collection tutorial
  • java concurrency tutorial
  • java design pattern
  • Java Enum
  • Java file tutorials
  • Java Functional Programming
  • Java Installation Guide
  • Java Interview Question
  • Java interview questions
  • Java IO interview question
  • java io tutorial
  • java map tutorials
  • java modules
  • Java Multithreading Tutorial
  • Java networking tutorial
  • Java Operator tutorial
  • Java programming Tutorial
  • Java String tutorial
  • Java7
  • JavaScript
  • JavaScript Interview Question
  • JavaScript Tutorial
  • JDBC
  • JEE Interview Questions
  • Jenkins
  • JMS
  • JPA
  • jQuery
  • JSON
  • JSP
  • JSP Interview Question
  • JSTL
  • JUnit
  • JVM
  • Keras
  • keystore
  • Kotlin
  • kubernetes
  • lambda expression
  • Laraval
  • learning
  • linked list
  • Linux
  • Log4j
  • logging
  • Lombok
  • LSAT
  • Mac OS X
  • machine learning
  • Mathematics
  • Matlab
  • Maven
  • MERN stack
  • Messaging
  • Microservices
  • Microsoft
  • Microsoft Azure Platform
  • Microsoft Excel
  • Microsoft Power BI
  • Mockito
  • MongoDB
  • MysQL
  • MySQL tutorial example
  • nested class
  • neural network
  • Next.js
  • NFT
  • NLP
  • Node.js
  • nslookup
  • object oriented programming
  • OCAJP
  • OCMJEA
  • OCPJP
  • offers
  • Oracle
  • Perl
  • personal development
  • Photoshop
  • PHP
  • pluralsight
  • PostgerSQL
  • postman
  • Powerpoint
  • programmers
  • programming
  • programming problems
  • Project Management
  • projects
  • Prompt Engineering
  • Python
  • Pytorch
  • Quarkus
  • questions
  • Queue
  • R programming
  • React
  • React Hooks
  • react native
  • Record
  • Recursion
  • Redux
  • regular expression example
  • REST tutorials
  • Review
  • RoadMap
  • Ruby
  • Salesforce
  • SAT
  • Scala
  • Scala Interview Questions
  • Scanner
  • scripting
  • Scrum
  • Scrum Master Certification
  • Selenium
  • SEO
  • Serialization
  • Servlet
  • Servlet Interview Questions
  • Set
  • shell scripting
  • smart contracts
  • Snowflake SnowPro Certification
  • soft link
  • soft skills
  • software architecture
  • Solaris
  • Solidity
  • Sorting Algorithm
  • Spark
  • spring boot
  • Spring Certification
  • spring cloud
  • spring data jpa
  • spring framework
  • spring interview question
  • spring mvc
  • spring security
  • sql
  • SQL interview Question
  • SQL Joins
  • SQL SERVER
  • ssl
  • Static
  • Statistics
  • Stream
  • String
  • Struts
  • Swift
  • swing
  • switch case
  • system design
  • Tableau
  • Tailwind
  • TensorFlow
  • ternary operator
  • testing
  • thread
  • thread interview questions
  • Time series analysis
  • Tips
  • tomcat
  • tools
  • tree
  • TreeMap
  • troubleshooting
  • TypeScript
  • Udacity
  • Udemy
  • UI and UX Design
  • UML
  • unit testing
  • Unity 3D
  • Unix
  • unreal engine
  • Video Editing
  • Vuejs
  • web design
  • web development
  • web scrapping
  • Web Service
  • Whizlabs
  • Wix
  • xml
  • YAML
  • ZTM Academy

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Search This Blog

Best Online Learning Resources and Platforms

  • Coursera Plus (40% OFF)
  • Datacamp Sale (50% OFF)
  • AlgoMonster Lifetime Plan (50% OFF)
  • Udemy Sale (80% OFF)
  • Baeldung (33% OFF)
  • LabEx Sale (50% OFF)
  • Codecademy Sale (60% OFF)
  • Udacity Sale (50% OFF)
  • ZTM Academy Sale (66% OFF)
  • Frontend Masters Deal
  • Whizlabs Deal (70% OFF)

Javarevisited

Loading...

Spring Interview Prep List

  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses

Subscribe for Discounts and Updates

Follow

Interview Questions

  • core java interview questions
  • SQL interview questions
  • data structure interview question
  • coding interview questions
  • java collection interview questions
  • java design pattern interview questions
  • thread interview questions
  • hibernate interview questions
  • j2ee interview questions
  • Spring Interview Questions
  • object oriented programming questions

Followers

Blog Archive

  • ▼  2025 (554)
    • ▼  June (103)
      • JDBC - How to get Row and Column Count From Result...
      • Can You Create Instance of Abstract class in Java?...
      • How to convert String to Enum in Java? ValueOf Exa...
      • The Ultimate Guide to Package in Java? Examples
      • How to read a file line by line in Java? BufferedR...
      • Java Enum with Constructor Example
      • Could not create the Java virtual machine Invalid ...
      • ArrayList vs Vector in Java? Interview Question An...
      • The Ultimate Guide of Enum in Java - Examples
      • What is class file in Java? Example
      • Difference between static and non static nested cl...
      • How to read file in Java using Scanner Example - t...
      • Difference between throw vs throws in Java? Answer
      • How to read User Input from Console in Java? Scann...
      • How to Find IP address of localhost or a Server in...
      • 15 People Java Developers Should Follow on Twitter
      • Java Keyword Cheat Sheet - Meaning and Usage
      • Video example - Dijkstra's Algorithm shortest path...
      • How to remove duplicate(s) from linked list in Jav...
      • How to find Factorial in Java using Recursion and ...
      • How to calculate perimeter and area of square in J...
      • How to solve word break problem in Java using dyna...
      • How to calculate Compound Interest in Java? Compou...
      • How to check if a Number is Power of Two in Java? ...
      • [Solved] How to count Vowels and Consonants in Jav...
      • [Solved] How to convert Hexadecimal to Decimal, Bi...
      • How to create a Function to add two numbers in Jav...
      • [Solved] How to solve climbing stairs problem in J...
      • How to Search an Element in Java Array with Exampl...
      • [Solved] How to solve a coin change problem in Jav...
      • How to print a Right Triangle Pattern in Java - Ex...
      • [Solved] How to convert Decimal to Binary Number i...
      • [Solved] How to find all pairs which add up to a g...
      • 2 Ways to solve FizzBuzz in Java? [Example]
      • How to Find Highest Repeating Word from a File in ...
      • How to Check if Given Number is Prime in Java - Wi...
      • [Solved] How to Find 2 Largest Number from Integer...
      • [Solved] How to Check If a Given String has No Dup...
      • How to Find Greatest Common Divisor of two numbers...
      • How to calculate sum of all numbers in a given arr...
      • [Solved] 2 Ways to Find Duplicate Elements in a gi...
      • [Solved] How to reverse a String in place in Java?...
      • Top 10 Algorithms books Every Programmer Should Read
      • How to implement Level Order Traversal of Binary T...
      • How to Implement Binary Tree InOrder traversal in ...
      • How to remove duplicate characters from String in ...
      • How to find median of two sorted arrays in Java? E...
      • Fibonacci Series in Java Using Recursion
      • How to Reverse an Integer in Java without converti...
      • How to Find Nth Fibonacci Number in Java [Solved] ...
      • How to implement Linear Search Algorithm in Java? ...
      • How to implement Radix Sort in Java - Algorithm Ex...
      • How to implement Merge Sort Algorithm in Java [So...
      • Counting Sort in Java - Example
      • Top 22 Array Concepts Interview Questions Answers ...
      • How to use Deque Data Structure in Java? Example T...
      • How to find Kth Smallest Element in a Binary Searc...
      • How to find the maximum sum level in binary tree i...
      • How to Find Lowest Common Ancestor of a Binary Tre...
      • How to get the first and last item in an array in ...
      • Difference between array and Hashtable or HashMap ...
      • [Solved] How to find the Longest common prefix in ...
      • How to check if a node exists in a binary tree or...
      • How to use Recursion in JavaScript? Example Tutorial
      • How to find 2nd, 3rd or kth element from end in li...
      • 10 Examples of an Array in Java
      • How to Print all leaf Nodes of a Binary tree in Ja...
      • 10 Examples of Array Data Structure in Java
      • Top 40 Binary Tree Coding Interview Questions for ...
      • Top 25 Linked List Coding Interview Questions for ...
      • [Solved] How to check if two String are Anagram in...
      • How to create a String or int Array in Java? Examp...
      • How to Find/Print Leaf nodes in a Binary Tree in J...
      • How to check If two Strings Array are equal in Jav...
      • Top 5 Free Servlet, JSP, Java FX, and JDBC Course...
      • Top 6 Dynamic Programming Online Courses for Codin...
      • 5 Free Online Courses to Learn Kotlin in 2025 - Be...
      • Top 6 Free Courses to Learn Bootstrap Online for B...
      • Difference between Binary Tree, Binary Search Tre...
      • [Solved] How to Find Repeated Characters in a give...
      • How to solve Two Sum Array Problem in Java? Example
      • 6 Essential Data Structures Java Programmer should...
      • Post order traversal Algorithms for Binary Tree in...
      • How to check if an array includes a value in JavaS...
      • How to sort an Array in descending order in Java? ...
      • QuickSort Algorithm Example in Java using Recursio...
      • How to remove a number from an Integer Array in Ja...
      • How Binary Search Algorithm Works? Java Example wi...
      • How to declare and Initialize two dimensional Arra...
      • How to compare two Arrays in Java to check if they...
      • How to Convert or Print Array to String in Java? E...
      • How to implement PreOrder traversal of Binary Tree...
      • How to reverse a singly linked list in Java withou...
      • How to Reverse an Array in place in Java? Example ...
      • 5 Differences between an array and linked list in ...
      • How to code Binary Search Algorithm using Recursio...
      • Post Order Binary Tree Traversal in Java Without R...
      • 7 Examples to Sort One and Two Dimensional String ...
      • Insertion Sort Algorithm in Java with Example
      • How to Rotate an Array to Left or Right in Java? S...

Privacy

  • Privacy Policy
  • Terms & Conditions

Popular Posts

  • 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
  • How to fix "illegal start of expression" error in Java? Example
  • Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
  • 5 Examples of Formatting Float or Double Numbers to String in Java
  • Top 10 Frequently asked SQL Query Interview Questions Answers

Subscribe

Get new posts by email:
Subscribe

Tag » How To Reverse A Linked List