- Total Accepted: 84681
- Total Submissions: 341465
- Difficulty: Medium
- Contributors: Admin
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
分析
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 | /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * slow fast pointer * [1,2,3,4] 2 * [1,2,3,4,5] 3 * [1,2,3,4,5,6] 3 * ... */ class Solution { public : void reorderList(ListNode* head) { if (head == NULL || head->next == NULL) return ; ListNode* slow = head, * fast = head; while (fast && fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode* l1 = head; ListNode* l2 = reverse(slow->next); slow->next = NULL; ListNode dummy(0); ListNode* p = &dummy; bool sign = false ; while (l2){ if (sign){ p->next = l2; l2 = l2->next; } else { p->next = l1; l1 = l1->next; } p = p->next; sign = !sign; } p->next = l1; } ListNode* reverse(ListNode* head){ if (head == NULL || head->next == NULL) return head; ListNode* p = NULL, * cur = head; while (cur){ ListNode* tmp = cur->next; cur->next = p; p = cur; cur = tmp; } return p; } }; |