Вы находитесь на странице: 1из 7

3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops

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

How to Reverse a linked list in Java using Recursion and Loops


There are a couple of algorithms exists to
reverse a singly linked list in Java e.g. You can ManageMainframe
use the threepointers approach or solve this
problem using a stack, or simply using recursion LogStreams
without the external stack. As I had pointed out
on the earlier post about linked list, that Weprovideatoolforeasy
reversing a linked list is one of the most popular Operlogaccesstorelevant
data structure interview question, based on information.Tryitnow.
linked list, which means, you just can't afford
to prepare this one, before going for any betasystemsdci.com
programming interview. Despite being so
common, It's not easy to solve this problem on
the fly. Many Java programmer struggles to reverse a linked list using both iteration and
recursion, which makes this question very useful for filtering programmers who can code and
who are not so good with coding. Indeed, this is one of the confusing algorithms to understand
and it's not easy to grasp, especially if you haven't practiced linked list based questions e.g.
finding middle node of linked list in one pass or inserting and removing an element from
linked list data structure.

Since Java programmer gets a linked list implementation in the form of


java.util.LinkedList, they never bother to do this exercise by hand. Yes, there are
some exceptions but many Java programmer doesn't focus enough on data structure and hand
coding, which is really important to improve your problemsolving skills for the interview.

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.

Before going for a programming/coding interview, It's absolutely necessary to do as much


practice in data structure and algorithm as possible to take advantage of all the knowledge
available. This will improve your thinking ability, problemsolving skill and you will be more
comfortable with dealing with the unknown set of problems. This advice is irrespective of
whether you are a Java, C++, or Python developer.

Interview Questions

core java interview question (163)


data structure and algorithm (50)
Coding Interview Question (34)
SQL Interview Questions (27)
thread interview questions (22)
database interview questions (18)
Pureit Water Purier servlet interview questions (17)
collections interview questions (15)

Advanced 6-stage Purication through RO + UV Technology spring interview questions (9)


Programming interview question (6)
hibernate interview questions (5)

Translate this blog

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

date and time tutorial (19)


FIX protocol tutorial (16)
java collection tutorial (54)
State Bank PO 2017 Material java IO tutorial (25)
Java JSON tutorial (6)
Prepared by Rohit Agarwal
Java multithreading Tutorials (37)
Java Programming Tutorials (27)
Java xml tutorial (9)

Download Free State Bank PO 2017 Exam Prep Material


used by 1000s of Students.

talentsprint.com

This class is similar to the SinglyLinkedListclass, which we have seen in how to


implement linked list in Java using generics (see here), with two more methods for reversing
linked list using iteration and recursion.

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 )

head=newNode(data); 2016 ( 166 )


return; 2015 ( 126 )
} 2014 ( 100 )
tail().next=newNode(data);
2013 ( 127 )
}
2012 ( 214 )

2011 ( 135 )
privateNodetail(){
2010 ( 30 )
Nodetail=head;

//Findlastelementoflinkedlistknownastail
while(tail.next!=null){ Pages
tail=tail.next;
Privacy Policy
}
returntail; Copyright by Javin Paul 20102016. Powered by
Blogger.


@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

When to use ArrayList vs LinkedList in Java? (answer)


How to convert linked list to an array in Java? (example)
How to find the first and last element of linked list in Java? (solution)
How to search element inside linked list in Java? (solution)
What is the difference between LinkedList and ArrayList in Java? (answer)
How to reverse an array in place in Java? (solution)
Top 30 Arraybased Interview Questions for Programmers (list)
Top 5 Books to Learn Data Structure and Algorithms (books)
Top 5 Books for Programming and Coding Interviews (books)

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.

State Bank PO 2017 Material


Prepared by Rohit Agarwal

Download Free State Bank PO 2017 Exam Prep Material


used by 1000s of Students.

talentsprint.com

You might like:


Why multiple inheritances are not supported in Java
What is the real use of Method Overloading in Java or Programming?
Difference between Wait and Sleep, Yield in Java
Top 30 Programming questions asked in Interview Java C C++ Answers

Recommendedby

Posted by Javin Paul +9 Recommend this on Google

Labels: core java , data structure and algorithm , interview questions

2 comments :
Common Man Protection Force said...
hey you are wrong, we can access thru the index

public class LinkedListDemo {

public static void main(String[] args) {

// create a LinkedList
LinkedList list = new LinkedList();

// add some elements


list.add("Hello");
list.add(2);
list.add("Chocolate");
list.add("10");

http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 6/7
3/28/2017 HowtoReversealinkedlistinJavausingRecursionandLoops

// print the list


System.out.println("LinkedList:" + list);

// print element at index 3


System.out.println("Element at index 3 :" + list.get(3));
}
}

March 23, 2017 at 7:53 AM

Bhagyashree Dhavalshankh said...


Thank you for illustration.

March 23, 2017 at 11:26 PM

Post a Comment

Enteryourcomment...

Commentas: rajashekarbhimanathini(Google) Signout


Publish Preview Notifyme

Newer Post Home Older Post

Subscribe to: Post Comments ( Atom )

RelatedBooksforFurtherReading

CrackingtheCoding DataStructuresand DataStructuresand Algorithms(4thEdition)


Interview:189Programmin AlgorithmsMadeEasyin AlgorithmsinJava(2ndEdi

$26.79 $39.95 $36.16 $44.99 $48.09 $64.99 $64.54 $89.99

(365) (106) (101) (204)

IntroductiontoAlgorithms,3rd DataStructuresand Logic,SetsAndRecursion Recursion


Edition(MITPress) AlgorithmsMadeEasy:

$90.83 $99.00 $26.99 $44.99 $39.94 $212.95

(439) (173) (7) $6.50

AdsbyAmazon

http://javarevisited.blogspot.in/2017/03/howtoreverselinkedlistinjavausingiterationandrecursion.html 7/7

Вам также может понравиться