File tree 2 files changed +62
-17
lines changed
2 files changed +62
-17
lines changed Original file line number Diff line number Diff line change 1
1
#include <stdio.h>
2
2
#include <stdlib.h>
3
3
4
+
4
5
struct ListNode {
5
6
int val ;
6
7
struct ListNode * next ;
7
8
};
8
9
9
- static struct ListNode * rotateRight (struct ListNode * head , int k )
10
+ struct ListNode * rotateRight (struct ListNode * head , int k )
10
11
{
11
- if (head == NULL || k <= 0 ) {
12
+ if (head == NULL ) {
12
13
return head ;
13
14
}
14
15
16
+ int len = 0 ;
15
17
struct ListNode dummy ;
16
18
dummy .next = head ;
17
- struct ListNode * prev = & dummy ;
18
- struct ListNode * p = head ;
19
- int len = 0 ;
20
- while (p != NULL ) {
21
- prev = p ;
22
- p = p -> next ;
19
+ struct ListNode * tail = & dummy ;
20
+ while (tail -> next != NULL ) {
21
+ tail = tail -> next ;
23
22
len ++ ;
24
23
}
25
24
26
- struct ListNode * last = prev ;
27
- prev = & dummy ;
28
- p = head ;
25
+ struct ListNode * prev = & dummy ;
26
+ struct ListNode * p = head ;
29
27
len = len - (k % len );
30
28
while (len -- > 0 ) {
31
29
prev = p ;
@@ -36,23 +34,22 @@ static struct ListNode* rotateRight(struct ListNode* head, int k)
36
34
/* deletion */
37
35
prev -> next = NULL ;
38
36
/* insertion */
39
- last -> next = dummy . next ;
40
- dummy . next = p ;
37
+ tail -> next = head ;
38
+ head = p ;
41
39
}
42
40
43
- return dummy . next ;
41
+ return head ;
44
42
}
45
43
46
44
int main (int argc , char * * argv )
47
45
{
48
- int i ;
49
- struct ListNode * p , * prev , dummy , * list ;
50
-
51
46
if (argc < 2 ) {
52
47
fprintf (stderr , "Usage: ./test k n1 n2...\n" );
53
48
exit (-1 );
54
49
}
55
50
51
+ int i ;
52
+ struct ListNode * p , * prev , dummy , * list ;
56
53
dummy .next = NULL ;
57
54
prev = & dummy ;
58
55
for (i = 2 ; i < argc ; i ++ ) {
Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+
3
+ using namespace std ;
4
+
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * struct ListNode {
8
+ * int val;
9
+ * ListNode *next;
10
+ * ListNode() : val(0), next(nullptr) {}
11
+ * ListNode(int x) : val(x), next(nullptr) {}
12
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
13
+ * };
14
+ */
15
+ class Solution {
16
+ public:
17
+ ListNode* rotateRight (ListNode* head, int k) {
18
+ if (head == nullptr ) {
19
+ return head;
20
+ }
21
+
22
+ int len = 0 ;
23
+ ListNode dummy;
24
+ dummy.next = head;
25
+ ListNode *tail = &dummy;
26
+ while (tail->next != nullptr ) {
27
+ len++;
28
+ tail = tail->next ;
29
+ }
30
+
31
+ ListNode *prev = &dummy;
32
+ ListNode *p = head;
33
+ k = k % len;
34
+ for (int i = 0 ; i < len - k; i++) {
35
+ prev = p;
36
+ p = p->next ;
37
+ }
38
+
39
+ if (p != nullptr ) {
40
+ /* deletion */
41
+ prev->next = tail->next ;
42
+ /* insertion */
43
+ tail->next = head;
44
+ head = p;
45
+ }
46
+ return head;
47
+ }
48
+ };
You can’t perform that action at this time.
0 commit comments