File tree Expand file tree Collapse file tree 2 files changed +35
-25
lines changed
092_reverse_linked_list_ii Expand file tree Collapse file tree 2 files changed +35
-25
lines changed Original file line number Diff line number Diff line change @@ -8,27 +8,25 @@ struct ListNode {
8
8
9
9
static struct ListNode * reverseBetween (struct ListNode * head , int m , int n )
10
10
{
11
- int len = n - m + 1 ;
12
- if (len == 1 ) {
13
- return head ;
14
- }
15
-
11
+ int i ;
16
12
struct ListNode dummy ;
17
- struct ListNode * p = head ;
18
13
struct ListNode * prev = & dummy ;
19
- prev -> next = p ;
20
- while ( -- m > 0 ) {
21
- prev = p ;
22
- p = p -> next ;
14
+ prev -> next = head ;
15
+
16
+ for ( i = 1 ; i < m ; i ++ ) {
17
+ prev = prev -> next ;
23
18
}
24
19
25
- struct ListNode * q = p -> next ;
26
- while (-- len > 0 ) {
20
+ struct ListNode * p = prev -> next ;
21
+ for (i = m ; i < n ; i ++ ) {
22
+ struct ListNode * q = p -> next ;
23
+ /* deletion */
27
24
p -> next = q -> next ;
25
+ /* insertion */
28
26
q -> next = prev -> next ;
29
27
prev -> next = q ;
30
- q = p -> next ;
31
28
}
29
+
32
30
return dummy .next ;
33
31
}
34
32
Original file line number Diff line number Diff line change @@ -6,27 +6,39 @@ struct ListNode {
6
6
struct ListNode * next ;
7
7
};
8
8
9
- static void recursive ( struct ListNode * dummy , struct ListNode * prev , struct ListNode * p )
9
+ static struct ListNode * recursive ( struct ListNode * prev , struct ListNode * p )
10
10
{
11
- if (p != NULL ) {
12
- prev -> next = p -> next ;
13
- p -> next = dummy -> next ;
14
- dummy -> next = p ;
15
- recursive (dummy , prev , prev -> next );
11
+ if (p == NULL ) {
12
+ return prev ;
16
13
}
14
+
15
+ struct ListNode * q = p -> next ;
16
+ p -> next = prev ;
17
+ return recursive (p , q );
17
18
}
18
19
19
20
static struct ListNode * reverseList (struct ListNode * head )
20
21
{
21
- if (head == NULL ) {
22
- return NULL ;
22
+ return recursive (NULL , head );
23
+ }
24
+
25
+
26
+ /* Iteration */
27
+ #if 0
28
+ static struct ListNode * reverseList (struct ListNode * head )
29
+ {
30
+ struct ListNode * prev = NULL ;
31
+ struct ListNode * p = head ;
32
+ while (p != NULL ) {
33
+ struct ListNode * q = p -> next ;
34
+ p -> next = prev ;
35
+ prev = p ;
36
+ p = q ;
23
37
}
24
38
25
- struct ListNode dummy ;
26
- dummy .next = head ;
27
- recursive (& dummy , head , head -> next );
28
- return dummy .next ;
39
+ return prev ;
29
40
}
41
+ #endif
30
42
31
43
int main (int argc , char * * argv )
32
44
{
You can’t perform that action at this time.
0 commit comments