You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/**It works out the best to set up a debug point and visualize this process:
18
-
* e.g. 1->2->3-null
19
-
* at the end of the first iteration of the while loop, the status is like this:
20
-
* newHead: 1->null
21
-
* head: 2->3-null
22
-
* then it continues the iteration.*/
23
-
ListNodenewHead = null;
24
-
while (head != null) {
25
-
ListNodenext = head.next;
26
-
head.next = newHead;
27
-
newHead = head;
28
-
head = next;
11
+
publicstaticclassSolution1 {
12
+
/**
13
+
* creating a newHead = null is a very common/smart way to handle such cases, the logic flows out very naturally:
14
+
* create a new node called "next" to hold current head's next node
15
+
* then we could redirect head's next pointer to point to newHead which is head's previous node
16
+
* the above two steps finished the reversion, to continue this process until we reach the end of the original list,
17
+
* we'll assign current "head" to new "newHead", and current "next" to be new "head" for the next iteration, here's the code
18
+
*/
19
+
publicListNodereverseList(ListNodehead) {
20
+
/**It works out the best to set up a debug point and visualize this process:
21
+
* e.g. 1->2->3-null
22
+
* at the end of the first iteration of the while loop, the status is like this:
23
+
* newHead: 1->null
24
+
* head: 2->3-null
25
+
* then it continues the iteration.*/
26
+
ListNodenewHead = null;
27
+
while (head != null) {
28
+
ListNodenext = head.next;
29
+
head.next = newHead;
30
+
newHead = head;
31
+
head = next;
32
+
}
33
+
returnnewHead;
29
34
}
30
-
returnnewHead;
31
35
}
32
36
33
-
/**
34
-
* following the above iterative version, the recursive solution flows out so naturally, basically, we just replaced the while loop with a recursive function
35
-
* still, a null newHead proves to be very helpful.
0 commit comments