1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
struct ListNode* (struct ListNode* head){ struct ListNode* pre = NULL; struct ListNode* cur = head; struct ListNode* next = NULL; while (cur != NULL){ next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; }
void reorderList(struct ListNode* head){ if (head == NULL || head->next == NULL){ return; } struct ListNode* dummyHead = (struct ListNode*) malloc(sizeof(struct ListNode)); dummyHead->next = head; struct ListNode* fast = head; struct ListNode* slow = head; while (fast->next != NULL && fast->next->next!= NULL) { slow = slow->next; fast = fast->next->next; }
struct ListNode* p = slow; struct ListNode* q = p->next; if (q == NULL) { return head; } q = reverse(q); p->next = NULL; p = dummyHead->next; struct ListNode* tail = dummyHead; int flag = 0; while (p != NULL && q != NULL) { if (flag == 0) { tail->next = p; tail = p; p = p->next; flag = 1; }else{ tail->next = q; tail = q; q = q->next; flag = 0; } } if (p != NULL) { tail->next = p; } if (q != NULL) { tail->next = q; } return dummyHead->next; }
|
近期评论