Skip to content

Commit f583b44

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent b770fde commit f583b44

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

061_rotate_list/rotate_list.c

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,40 @@ struct ListNode {
66
struct ListNode *next;
77
};
88

9-
static struct ListNode* rotateRight(struct ListNode* head, int k) {
9+
static struct ListNode* rotateRight(struct ListNode* head, int k)
10+
{
1011
if (head == NULL || k <= 0) {
1112
return head;
1213
}
1314

1415
struct ListNode dummy;
1516
dummy.next = head;
1617
struct ListNode *prev = &dummy;
17-
struct ListNode *last = &dummy;
1818
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) {
2821
prev = p;
2922
p = p->next;
30-
k--;
23+
len++;
3124
}
3225

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) {
3531
prev = p;
3632
p = p->next;
3733
}
3834

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;
4341
}
42+
4443
return dummy.next;
4544
}
4645

@@ -59,13 +58,11 @@ int main(int argc, char **argv)
5958
for (i = 2; i < argc; i++) {
6059
p = malloc(sizeof(*p));
6160
int n = atoi(argv[i]);
62-
printf("%d ", n);
6361
p->val = n;
6462
p->next = NULL;
6563
prev->next = p;
6664
prev = p;
6765
}
68-
putchar('\n');
6966

7067
list = rotateRight(dummy.next, atoi(argv[1]));
7168
for (p = list; p != NULL; p = p->next) {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy