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
Copy file name to clipboardExpand all lines: 206. Reverse Linked List.md
+14-13
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,5 @@
1
-
/**
1
+
## Problem description
2
+
2
3
Reverse a singly linked list.
3
4
4
5
Example:
@@ -8,8 +9,10 @@ Output: 5->4->3->2->1->NULL
8
9
Follow up:
9
10
10
11
A linked list can be reversed either iteratively or recursively. Could you implement both?
11
-
**/
12
12
13
+
## Iterative
14
+
15
+
```cpp
13
16
//iterative
14
17
/**
15
18
* Definition for singly-linked list.
@@ -37,12 +40,12 @@ class Solution {
37
40
return prev;
38
41
}
39
42
};
43
+
```
40
44
45
+
## Recursive
46
+
The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part?
41
47
42
-
//recursive
43
-
/**
44
-
Approach #2 (Recursive) [Accepted]
45
-
The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part? Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø
48
+
Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø
46
49
47
50
Assume from node nk+1 to nm had been reversed and you are at node nk.
48
51
@@ -57,9 +60,7 @@ nk.next.next = nk;
57
60
Be very careful that n1's next must point to Ø.
58
61
If you forget about this, your linked list has a cycle in it.
59
62
This bug could be caught if you test your code with a linked list of size 2.
60
-
**/
61
63
62
-
/**
63
64
Complexity analysis
64
65
65
66
Time complexity : O(n).
@@ -68,13 +69,13 @@ Assume that nn is the list's length, the time complexity is O(n).
68
69
Space complexity : O(n).
69
70
The extra space comes from implicit stack space due to recursion.
70
71
The recursion could go up to nn levels deep.
71
-
**/
72
72
73
-
/**
73
+
74
74
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Reverse Linked List.
75
+
75
76
Memory Usage: 9.3 MB, less than 10.03% of C++ online submissions for Reverse Linked List.
0 commit comments