File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
my-folder/problems/reverse_linked_list Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ struct ListNode * reverseList (struct ListNode * head ) {
2
+ struct ListNode * prev = head ;
3
+ if (!head ) {
4
+ return 0 ;
5
+ }
6
+ struct ListNode * current = head -> next ;
7
+ if (!current ) {
8
+ prev -> next = 0 ;
9
+ return prev ;
10
+ }
11
+ struct ListNode * next = current -> next ;
12
+ if (!next ) {
13
+ current -> next = prev ;
14
+ prev -> next = 0 ;
15
+ return current ;
16
+ }
17
+
18
+ prev -> next = 0 ;
19
+ current -> next = prev ;
20
+
21
+ while (1 ) {
22
+ // Start state
23
+ // (0; NULL) (1; 0) (2; 3)
24
+ prev = current ;
25
+ // (1; 0) (1; 0) (2; 3)
26
+ current = next ;
27
+ // (1; 0) (2; 3) (2; 3)
28
+ next = next -> next ;
29
+ // (1; 0) (2; 3) (3; 4)
30
+ current -> next = prev ;
31
+ // End state
32
+ // (1; 0) (2; 1) (3; 4)
33
+
34
+ if (!next ) {
35
+ return current ;
36
+ }
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments