forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Leo Ma <[email protected]>
- Loading branch information
1 parent
9dad347
commit 6385d6a
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test rotate_list.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
struct ListNode { | ||
int val; | ||
struct ListNode *next; | ||
}; | ||
|
||
static struct ListNode* rotateRight(struct ListNode* head, int k) { | ||
if (head == NULL || k <= 0) { | ||
return head; | ||
} | ||
|
||
struct ListNode dummy; | ||
dummy.next = head; | ||
struct ListNode *prev = &dummy; | ||
struct ListNode *last = &dummy; | ||
struct ListNode *p = head; | ||
int count = k; | ||
while (k > 0) { | ||
if (p == NULL) { | ||
int length = count - k; | ||
prev = &dummy; | ||
p = head; | ||
k = count % length; | ||
if (k == 0) break; | ||
} | ||
prev = p; | ||
p = p->next; | ||
k--; | ||
} | ||
|
||
while (p != NULL) { | ||
last = last->next; | ||
prev = p; | ||
p = p->next; | ||
} | ||
|
||
if (last != &dummy) { | ||
prev->next = head; | ||
dummy.next = last->next; | ||
last->next = NULL; | ||
} | ||
return dummy.next; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
int i; | ||
struct ListNode *p, *prev, dummy, *list; | ||
|
||
if (argc < 2) { | ||
fprintf(stderr, "Usage: ./test k n1 n2...\n"); | ||
exit(-1); | ||
} | ||
|
||
dummy.next = NULL; | ||
prev = &dummy; | ||
for (i = 2; i < argc; i++) { | ||
p = malloc(sizeof(*p)); | ||
int n = atoi(argv[i]); | ||
printf("%d ", n); | ||
p->val = n; | ||
p->next = NULL; | ||
prev->next = p; | ||
prev = p; | ||
} | ||
putchar('\n'); | ||
|
||
list = rotateRight(dummy.next, atoi(argv[1])); | ||
for (p = list; p != NULL; p = p->next) { | ||
printf("%d ", p->val); | ||
} | ||
putchar('\n'); | ||
|
||
return 0; | ||
} |