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:
void reorderList(ListNode *head) {
if(head == NULL || head->next == NULL) return;
// Patition to two lists.
ListNode *listone = head;
ListNode *listtwo = head;
ListNode *slow = head;
ListNode *fast = head;
int length = 0;
while(slow != NULL) {
slow = slow->next;
length ++;
}
for(int ii = 0; ii < (length - 1) / 2; ii ++) {
fast = fast->next;
}
listtwo = fast->next;
fast->next = NULL;
// Reverse listtwo.
ListNode *pre = NULL;
ListNode *current = listtwo;
ListNode *after = listtwo->next;
while(current != NULL && after != NULL) {
current->next = pre;
pre = current;
current = after;
after = after->next;
}
current->next = pre;
listtwo = current;
// Merge two lists.
current = listone;
while(listtwo != NULL) {
// Insert listtwo after current.
ListNode *temp = current->next;
current->next = listtwo;
current = temp;
temp = listtwo->next;
listtwo->next = current;
listtwo = temp;
}
}
};