File tree Expand file tree Collapse file tree 1 file changed +17
-20
lines changed Expand file tree Collapse file tree 1 file changed +17
-20
lines changed Original file line number Diff line number Diff line change @@ -6,41 +6,40 @@ struct ListNode {
6
6
struct ListNode * next ;
7
7
};
8
8
9
- static struct ListNode * rotateRight (struct ListNode * head , int k ) {
9
+ static struct ListNode * rotateRight (struct ListNode * head , int k )
10
+ {
10
11
if (head == NULL || k <= 0 ) {
11
12
return head ;
12
13
}
13
14
14
15
struct ListNode dummy ;
15
16
dummy .next = head ;
16
17
struct ListNode * prev = & dummy ;
17
- struct ListNode * last = & dummy ;
18
18
struct ListNode * p = head ;
19
- int count = k ;
20
- while (k > 0 ) {
21
- if (p == NULL ) {
22
- int length = count - k ;
23
- prev = & dummy ;
24
- p = head ;
25
- k = count % length ;
26
- if (k == 0 ) break ;
27
- }
19
+ int len = 0 ;
20
+ while (p != NULL ) {
28
21
prev = p ;
29
22
p = p -> next ;
30
- k -- ;
23
+ len ++ ;
31
24
}
32
25
33
- while (p != NULL ) {
34
- last = last -> next ;
26
+ struct ListNode * last = prev ;
27
+ prev = & dummy ;
28
+ p = head ;
29
+ len = len - (k % len );
30
+ while (len -- > 0 ) {
35
31
prev = p ;
36
32
p = p -> next ;
37
33
}
38
34
39
- if (last != & dummy ) {
40
- prev -> next = head ;
41
- dummy .next = last -> next ;
42
- last -> next = NULL ;
35
+ if (p != NULL ) {
36
+ /* deletion */
37
+ prev -> next = NULL ;
38
+ /* insertion */
39
+ last -> next = dummy .next ;
40
+ dummy .next = p ;
43
41
}
42
+
44
43
return dummy .next ;
45
44
}
46
45
@@ -59,13 +58,11 @@ int main(int argc, char **argv)
59
58
for (i = 2 ; i < argc ; i ++ ) {
60
59
p = malloc (sizeof (* p ));
61
60
int n = atoi (argv [i ]);
62
- printf ("%d " , n );
63
61
p -> val = n ;
64
62
p -> next = NULL ;
65
63
prev -> next = p ;
66
64
prev = p ;
67
65
}
68
- putchar ('\n' );
69
66
70
67
list = rotateRight (dummy .next , atoi (argv [1 ]));
71
68
for (p = list ; p != NULL ; p = p -> next ) {
You can’t perform that action at this time.
0 commit comments