Reverse a linked list
Input list :
1->2->3->4->||
Output list :
4->3->2->1->||
Code:
Node reverse(Node head) {
Node prev = null;
Node current = head;
while (current != null) {
Node temp = current.next;
current.next = prev;
prev = current;
current = temp;
}
head = prev;
return head;
}
Calling function:
head = list.reverse(head);
Illustration:
(note : images in order left column first followed by right column)
i) Initialization and execution of first while loop

ii) Execution of second while loop
iii) Execution of final while loop and termination

1->2->3->4->||
Output list :
4->3->2->1->||
Code:
Node reverse(Node head) {
Node prev = null;
Node current = head;
while (current != null) {
Node temp = current.next;
current.next = prev;
prev = current;
current = temp;
}
head = prev;
return head;
}
Calling function:
head = list.reverse(head);
Illustration:
(note : images in order left column first followed by right column)
i) Initialization and execution of first while loop

ii) Execution of second while loop
iii) Execution of final while loop and termination


Comments
Post a Comment