标签:
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}
.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* newHead = NULL; ListNode* next = NULL; while(cur){ next = cur->next; cur->next = newHead; newHead = cur; cur = next; } return newHead; } void reorderList(ListNode* head) { if(head==NULL || head->next==NULL){ return; } ListNode* slow = head; ListNode* fast = head; ListNode* pre = NULL; while(fast){ pre = slow; slow = slow->next; fast->next ? fast = fast->next->next : fast = NULL; } pre->next = NULL; ListNode* head2 = reverseList(slow); ListNode* cur = head; ListNode* cur_next = NULL; ListNode* cur2 = head2; ListNode* cur2_next = NULL; while(cur2){ cur_next = cur->next; cur2_next = cur2->next; cur->next = cur2; cur2->next = cur_next; cur = cur_next; cur2 = cur2_next; } } };
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5041732.html