How To Reverse A Singly Linked List In Java Without Recursion ... - Java67
Maybe your like
Pages
- Home
- core java
- spring
- online courses
- thread
- java 8
- coding
- sql
- books
- oop
- interview
- certification
- free resources
- best
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.
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)
2 comments:
TrOubleshootersMarch 2, 2021 at 5:50 PMwhile (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
Tales to TravelDecember 21, 2021 at 4:06 PMI 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
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
FollowInterview 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
- ► 2024 (192)
- ► December (30)
- ► October (32)
- ► September (31)
- ► August (12)
- ► July (3)
- ► June (2)
- ► May (9)
- ► April (3)
- ► March (28)
- ► February (3)
- ► January (39)
- ► 2023 (380)
- ► December (1)
- ► November (2)
- ► October (4)
- ► September (154)
- ► August (12)
- ► July (23)
- ► May (9)
- ► April (116)
- ► March (15)
- ► February (35)
- ► January (9)
- ► 2022 (164)
- ► December (18)
- ► October (1)
- ► September (1)
- ► August (45)
- ► July (27)
- ► June (11)
- ► May (19)
- ► April (16)
- ► March (12)
- ► February (6)
- ► January (8)
- ► 2021 (104)
- ► December (6)
- ► November (2)
- ► October (13)
- ► September (18)
- ► August (31)
- ► July (34)
- ► 2020 (10)
- ► August (2)
- ► July (1)
- ► June (1)
- ► April (3)
- ► March (1)
- ► February (2)
- ► 2019 (9)
- ► December (1)
- ► November (1)
- ► October (1)
- ► September (1)
- ► July (1)
- ► June (1)
- ► April (3)
- ► 2018 (9)
- ► November (1)
- ► April (8)
- ► 2017 (4)
- ► October (1)
- ► September (2)
- ► April (1)
- ► 2015 (8)
- ► July (1)
- ► June (1)
- ► May (1)
- ► February (5)
- ► 2012 (1)
- ► September (1)
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:
SubscribeTag » How To Reverse A Linked List
-
Reverse A Linked List - GeeksforGeeks
-
Reverse A Linked List - DigitalOcean
-
Reversing A Linked List: Easy As 1, 2, 3 | By Sergey Piterman - Medium
-
Reverse Linked List - LeetCode
-
Reverse A Linked List - InterviewBit
-
Reversing A Linked List In Java - Baeldung
-
Reverse A Singly Linked List - Coderust: Hacking The Coding Interview
-
Tutorial: How To Reverse A Linked List In C++
-
How To Reverse Linked List In Java - Javatpoint
-
Reverse A Linked List C++ Code (Iterative And Recursive) - FavTutor
-
Reverse A Single Linked List - YouTube
-
Reverse A Linked List | Iterative - YouTube
-
Reverse A Linked List From Position M To N - AfterAcademy
-
Reverse A Linked List | HackerRank
TrOubleshooters
Tales to Travel