|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +struct ListNode { |
| 5 | + int val; |
| 6 | + struct ListNode *next; |
| 7 | +}; |
| 8 | + |
| 9 | +struct ListNode *Helper(struct ListNode **forward, struct ListNode *node) { |
| 10 | + if (node == NULL || node->next == NULL) return node; |
| 11 | + |
| 12 | + struct ListNode *tail = Helper(forward, node->next); |
| 13 | + |
| 14 | + if (*forward == tail || (*forward)->next == tail) return tail; |
| 15 | + |
| 16 | + struct ListNode *t = (*forward)->next; |
| 17 | + (*forward)->next = tail; |
| 18 | + *forward = t; |
| 19 | + tail->next = t; |
| 20 | + |
| 21 | + return node; |
| 22 | +} |
| 23 | + |
| 24 | +void reorderList(struct ListNode* head) { |
| 25 | + if (head == NULL) return; |
| 26 | + struct ListNode *p = head; |
| 27 | + struct ListNode *mid = Helper(&p, head); |
| 28 | + mid->next = NULL; |
| 29 | +} |
| 30 | + |
| 31 | +struct ListNode *createNode(int new_data) { |
| 32 | + struct ListNode *new_node = (struct ListNode *)malloc(sizeof(struct ListNode)); |
| 33 | + new_node->val = new_data; |
| 34 | + new_node->next = NULL; |
| 35 | + return new_node; |
| 36 | +} |
| 37 | + |
| 38 | +int main(){ |
| 39 | + /* test 1 */ |
| 40 | + struct ListNode *l1 = createNode(1); |
| 41 | + struct ListNode *p = l1; |
| 42 | + int i; |
| 43 | + for (i = 2; i <= 5; i++) { |
| 44 | + p->next = createNode(i); |
| 45 | + p = p->next; |
| 46 | + } |
| 47 | + p->next = NULL; |
| 48 | + |
| 49 | + printf("List 1: "); |
| 50 | + p = l1; |
| 51 | + while (p) { |
| 52 | + printf("%d->", p->val); |
| 53 | + p = p->next; |
| 54 | + } |
| 55 | + printf("NIL\n"); |
| 56 | + |
| 57 | + reorderList(l1); |
| 58 | + |
| 59 | + printf("Reorder: "); |
| 60 | + p = l1; |
| 61 | + while (p) { |
| 62 | + printf("%d->", p->val); |
| 63 | + p = p->next; |
| 64 | + } |
| 65 | + printf("NIL\n"); |
| 66 | + |
| 67 | + /* test 2 */ |
| 68 | + struct ListNode *l2 = createNode(1); |
| 69 | + p = l2; |
| 70 | + for (i = 2; i <= 6; i++) { |
| 71 | + p->next = createNode(i); |
| 72 | + p = p->next; |
| 73 | + } |
| 74 | + p->next = NULL; |
| 75 | + |
| 76 | + printf("List 2: "); |
| 77 | + p = l2; |
| 78 | + while (p) { |
| 79 | + printf("%d->", p->val); |
| 80 | + p = p->next; |
| 81 | + } |
| 82 | + printf("NIL\n"); |
| 83 | + |
| 84 | + reorderList(l2); |
| 85 | + |
| 86 | + printf("Reorder: "); |
| 87 | + p = l2; |
| 88 | + while (p) { |
| 89 | + printf("%d->", p->val); |
| 90 | + p = p->next; |
| 91 | + } |
| 92 | + printf("NIL\n"); |
| 93 | + |
| 94 | + return 0; |
| 95 | +} |
0 commit comments