Академический Документы
Профессиональный Документы
Культура Документы
Javarevisited
Blog about Java programming language, FIX Protocol, Tibco RV
Home core java spring hibernate collections multithreading design patterns interview questions coding data structure OOP books About Me
So, when it comes to design a whole system using Object oriented analysis and design e.g.
implementing a vending machine in Java, sometimes they fail to choose the correct data
structure and devising simple algorithms.
Interview Questions
SelectLanguage
Java Program to Reverse a singly linked list using recursion Poweredby Translate
and Iteration
A linked list is a data structure which contains nodes, every node keep data and pointer to
next node. This way linked list grows and can store as many elements as much memory allows
it. It's not like an array which requires a contiguous chunk of memory because here node can
be stored at any memory location.
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 1/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
This structure means, adding and removing elements in linked list is easy but searching an
element is expensive because you need to traverse entire list to find the element. It doesn't
help even if you know that element is the 5th node or 6th node because you cannot access
them by index like an array. This is the biggest difference between an array and linked list
data structure. In the array, searching the index is O(1) operation but in linked list searching
is O(n) operation.
Below code represent a singly linked list in Java, with limited operations. I have already
removed some nonrelevant code for performing different operations on linked list i.e.
checking if linked list is cyclic or not, inserting an element at the middle, and removing the
element. Since we don't need this code for reversing linked list, I have simply deleted them
for now. Java Tutorials
talentsprint.com
The reverseRecursively() method reverse the linked list using recursion. It uses the call
stack to store data, and once we reached tail, which becomes new head for the reversed
linked list, it starts adding nodes in reverse order. Look at some comments around those Search This Blog
methods, which will make you understand the algorithm of reversing linked list better. Search
It is said that a picture is worth a thousand word and it is very true in the case of problem
solving and understanding algorithms. Here are a diagram and flowchart to reverse a singly
linked list using recursion. It divides the list into two parts first node and rest of list,and then
link rest to head in reverse order. It then recursively applies same division until it reaches the
last node, at that point whole linked list, is reversed.
ThereverseIteratively()method reverses linked list using the threepointers approach Follow by Email
and using loops, that's why it is called iterative solution. It traverses through the linked list
Emailaddress... Submit
and adding nodes at the beginning of the singly linked list in each iteration. It uses three
reference variables (pointers) to keep track of previous, current, and next nodes.
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 2/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
Ads by
If you are not very familiar with linked list data structure or want to learn more about linked
list data structure, you should first read a good book on data structure and algorithm JavaTest
e.g.Data Structures and Algorithms Made Easy in Java by Narasimha Karumanchi, one of the
JavaInterview
best books to learn data structure and algorithms.
Followers
Followers(4169)Next
Follow
Blog Archive
2017 ( 53 )
March ( 13 )
Difference between Stack and Queue Data
Structure ...
10 Tools Used by Java Programming Developer in
Day...
How to Reverse a linked list in Java using
Recursi...
Java Class to represent Singly Linked List Top 30 Scala and Functional Programming
Interview ...
Here is our Java program solve this problem. As I said, it contains a class to represent singly
What is difference between SQL, TSQL and
linked list and it contains another class which has the main method for testing. That class
PL/SQL?
creates an instance of linked list and then call relevant methods to reverse the linked list by
Difference between First and Second Level
using iteration and recursion. Cache in...
How to enclose a list of values into single
quotes...
/** What is Method References in Java 8? An
Example
*JavaClasstorepresentsinglylinkedlistfordemonstrationpurpose.
*InordertounderstandHowtoreverselinkedlist,focusontwomethods Top 5 Advanced SQL Books for Experienced
Programme...
*reverseIteratively()andreverseRecursively().
How to Implement Stack in Java using Array and
Gen...
*@authorJavinPaul
How to find largest and smallest number from
*/ integ...
publicclassSinglyLinkedList{ Why we use Threads in Java?
privateNodehead;//Headisthefirstnodeinlinkedlist 10 Examples of curl Command in UNIX and Linux
February ( 16 )
publicvoidappend(Tdata){
if(head==null){ January ( 24 )
@Override
publicStringtoString(){
StringBuildersb=newStringBuilder();
Nodecurrent=head;
while(current!=null){
sb.append(current).append(">");
current=current.next;
}
if(sb.length()>=3){
sb.delete(sb.length()3,sb.length());//toremove>fromlastnode
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 3/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
}
returnsb.toString();
}
/**
*Reverselinkedlistusing3pointersapproachinO(n)time
*Itbasicallycreatesanewlistbyreversingdirection,and
*subsequentlyinserttheelementatthestartofthelist.
*/
publicvoidreverseIteratively(){
Nodecurrent=head;
Nodeprevious=null;
Nodeforward=null;
//traversinglinkedlistuntilthereisnomoreelement
while(current.next!=null){
//Savingreferenceofnextnode,sincewearechangingcurrentnode
forward=current.next;
//Insertingnodeatstartofnewlist
current.next=previous;
previous=current;
//Advancingtonextnode
current=forward;
}
head=current;
head.next=previous;
}
/*
*Reverseasinglylinkedlistusingrecursion.InrecursionStackis
*usedtostoredata.
*1.Traverselinkedlisttillwefindthetail,
*thatwouldbenewheadforreversedlinkedlist.
*/
privateNodereverseRecursively(Nodenode){
NodenewHead;
//basecasetailoforiginallinkedlist
if((node.next==null)){
returnnode;
}
newHead=reverseRecursively(node.next);
//reversethelinke.g.C>D>nullwillbenull
node.next.next=node;
node.next=null;
returnnewHead;
}
publicvoidreverseRecursively(){
head=reverseRecursively(head);
}
privatestaticclassNode{
privateNodenext;
privateTdata;
publicNode(Tdata){
this.data=data;
}
@Override
publicStringtoString(){
returndata.toString();
}
}
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 4/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
}
Test Class
Here is our test class, which will test both methods of reversing linked list,
reverseIteratively() and reverseRecursively(). We have first created a singly
linked list with 6 nodes ABCDEF, and first reversed them iteratively using 3 points
approach and later reversed the same list recursively. Since the same instance of the singly
linked list is reversed two times, you can see in the output that final list is same as original
linked list.
/**
*JavaprogramtotestcodeofreversingsinglylinkedlistinJava.
*Thistestclasstestbothiterativeandrecursivesolution.Since
*thesamelistisfirstreversedusingloops,andthenagainusingrecursion.
*Youcanseethatfinaloutputissameasoriginallinkedlist.
*@authorJavinPaul
*/
publicclassSinglyLinkedListTest{
publicstaticvoidmain(Stringargs[]){
SinglyLinkedListlinkedlist=getDefaultList();
System.out.println("linkedlistbeforereversing:"+linkedlist);
linkedlist.reverseIteratively();
System.out.println("linkedlistafterreversing:"+linkedlist);
linkedlist.reverseRecursively();
System.out.println("linkedlistafterreversingrecursively:"+linkedlist);
}
privatestaticSinglyLinkedListgetDefaultList(){
SinglyLinkedListlinkedlist=newSinglyLinkedList();
linkedlist.append("A");linkedlist.append("B");linkedlist.append("C");
linkedlist.append("D");linkedlist.append("E");linkedlist.append("F");
returnlinkedlist;
}
}
Output:
linkedlistbeforereversing:A>B>C>D>E>F
linkedlistafterreversing:F>E>D>C>B>A
linkedlistafterreversingrecursively:A>B>C>D>E>F
That's all on how to reverse a linked list in Java. We have seen two approaches to reverse
singly linked list, first using Iterations, which involves 3 pointers or reference variable; and
second, which reversed linked list using recursion. The reason, I have shared both approaches
because they are asked as a followup question, and it's always better to know both
approaches to make a good impression. By the way, if you can improve the algorithm, and can
find few more ways to reverse linked list, will always act as plus point for you. You can also
check out Cracking the code interview 6th Edition for more practice questions. It contains 189
coding interview questions based upon data structure, algorithms, and other topics.
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 5/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
Related linked list and data structure questions you may like to explore
Thanks for reading this interview question. If you like this article then please share with your
friends and colleagues. If you have any suggestions or feedback then please share your
comment.
talentsprint.com
Recommendedby
2 comments :
Common Man Protection Force said...
hey you are wrong, we can access thru the index
// create a LinkedList
LinkedList list = new LinkedList();
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 6/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops
Post a Comment
Enteryourcomment...
Publish Preview Notifyme
RelatedBooksforFurtherReading
AdsbyAmazon
http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 7/7