|
8 | 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
|
9 | 9 | * }
|
10 | 10 | */
|
| 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 | +* */ |
11 | 36 | class Solution {
|
12 | 37 | public ListNode reverseList(ListNode head) {
|
13 | 38 | ListNode prev=null;
|
|
0 commit comments