Skip to content

Commit

Permalink
Rotate list
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 4, 2017
1 parent 9dad347 commit 6385d6a
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 061_rotate_list/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rotate_list.c
77 changes: 77 additions & 0 deletions 061_rotate_list/rotate_list.c
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;
}

0 comments on commit 6385d6a

Please sign in to comment.