Skip to content

Commit b940fc6

Browse files
author
Sagar
committed
Added Explanation to reversing a linked list
1 parent f4cd969 commit b940fc6

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Linked List/reverse_linked_list.java

+25
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,31 @@
88
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
99
* }
1010
*/
11+
12+
/*Explaination of the code which reverses the linked list
13+
* --> Initially we are given the head of the linked list. The approach used here is that
14+
* for reversing the linked list we can take the user of three pointers
15+
*
16+
* --> These pointers are named as prev, curr, and right. Initially prev points to NULL, curr
17+
* points to the current node (node of which the pointer has to be reversed) and the right node
18+
* which always points to the node next to the current
19+
*
20+
* --> Idea here is that at each pass we will be reversing the pointer of the current node and
21+
* move all the pointers forward by one step
22+
*
23+
* --> So initially, the current node points to head node, it's pointer is reversed and is made to
24+
* point to he NULL, since now this first node becomes the last node.
25+
*
26+
* --> To move forward, prev is now at the location of current node, current node moves by
27+
* one step, by making it point to the location where right is pointing now. (Using right pointer
28+
* since the track of the next node is lost as we have reveresed the pointer).
29+
*
30+
* --> Loop stops when the current node becomes null. At the itereation, last node is being pointed
31+
* by prev, which is now the first node logically, so assign head to prev.
32+
*
33+
* --> Example input: 1->2->3->4->5
34+
* Output : 5->4->3->2->1
35+
* */
1136
class Solution {
1237
public ListNode reverseList(ListNode head) {
1338
ListNode prev=null;

0 commit comments

Comments
 (0)