Reverse a LinkedList Algorithm
Reversing a Linked List
Problem Statement: Reverse a Linked List.
Given a Linked List of Nodes :
1->2->3->4->5->6 , reverse it so that the output is 6->5->4->3->2->1
My Approach:
For this approach, we cannot the same LinkedListNode since it would point to the same memory location.
In the above example,
1 should point to null of the new List.
2 which is 1.next (original) should point to 1 of the new List.
3 which is 2.next (original) should point to 2 of the new List.
4 which is 3.next (original) should point to 3 of the new List.
5 which is 4.next (original) should point to 4 of the new List.
6 which is 5.next (original) should point to 5 of the new List.
This is where our logic ends.
1) LinkedListNode Class
For this approach, we cannot the same LinkedListNode since it would point to the same memory location.
In the above example,
1 should point to null of the new List.
2 which is 1.next (original) should point to 1 of the new List.
3 which is 2.next (original) should point to 2 of the new List.
4 which is 3.next (original) should point to 3 of the new List.
5 which is 4.next (original) should point to 4 of the new List.
6 which is 5.next (original) should point to 5 of the new List.
This is where our logic ends.
1) LinkedListNode Class
- This class has 2 Components of a Singly Linked List.
- Value of the node
- Pointer to the Next Node.
public class LinkedListNode
{
public int Val;
public LinkedListNode next;
public LinkedListNode(int x)
{
Val = x;
}
}
{
public int Val;
public LinkedListNode next;
public LinkedListNode(int x)
{
Val = x;
}
}
2) Actual Method to implement the logic.
public static LinkedListNode ReverseAListIterative(LinkedListNode head)
{
LinkedListNode previous = null;
LinkedListNode current = head;
while (current != null)
{
LinkedListNode temp = current.next;
current.next = previous;
previous = current;
current = temp;
}
return previous;
}
{
LinkedListNode previous = null;
LinkedListNode current = head;
while (current != null)
{
LinkedListNode temp = current.next;
current.next = previous;
previous = current;
current = temp;
}
return previous;
}
Comments
Post a Comment