patternjavaMinor
Reverse a linked list recursively
Viewed 0 times
listlinkedreverserecursively
Problem
This recursive calls
reverseList on each node of the linked list. When returned from the function call, it changes the next link to the previous node.public static Node reverseList(Node curNode , Node prevNode , Node reverseListHead)
{
//empty list
if(curNode == null)
{
return null;
}
//node with single element
if(curNode.next == null)
{
curNode.next = prevNode;
reverseListHead = curNode;
return reverseListHead;
}
reverseListHead = reverseList(curNode.next, curNode, reverseListHead);
curNode.next = prevNode;
return reverseListHead;
}Solution
Only one argument needed
First of all, your third argument
Next, if you change your algorithm slightly, you don't need the second argument either:
First of all, your third argument
reverseListHead should be a local variable because it is never used before being set.Next, if you change your algorithm slightly, you don't need the second argument either:
public static Node reverseList(Node head)
{
// Empty list or list with one element.
if (head == null || head.next == null) {
return head;
}
Node second = head.next;
Node reversedList = reverseList(second);
// The second node is now the tail of the reversed list,
// so when we append head to it, head becomes the new tail.
second.next = head;
head.next = null;
return reversedList;
}Code Snippets
public static Node reverseList(Node head)
{
// Empty list or list with one element.
if (head == null || head.next == null) {
return head;
}
Node second = head.next;
Node reversedList = reverseList(second);
// The second node is now the tail of the reversed list,
// so when we append head to it, head becomes the new tail.
second.next = head;
head.next = null;
return reversedList;
}Context
StackExchange Code Review Q#127842, answer score: 3
Revisions (0)
No revisions yet.