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}.
利用快慢两个指针将链表一分为二,针对第二个子链表求倒序,最后将两个子链表合并。
class Solution {
public:
void reorderList(ListNode *head) {
if(head == NULL)
return;
int size = 0;
ListNode *curNode = head;
while(curNode) {
size++;
curNode = curNode->next;
}
int step = size - (size >> 1); // pick the larger part
ListNode *cursor1 = head, *cursor2 = head;
while(--step)
cursor2 = cursor2->next;
ListNode *tmp = cursor2;
if(tmp != NULL) {
cursor2 = tmp->next;
tmp->next = NULL;
}
cursor2 = reverseList(cursor2);
while(cursor2) {
ListNode *tmp = cursor2;
cursor2 = cursor2->next;
tmp->next = cursor1->next;
cursor1->next = tmp;
cursor1 = tmp->next;
}
}
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return head;
ListNode *curNode = head;
while(curNode->next) {
ListNode *nextNode = curNode->next;
curNode->next = nextNode->next;
nextNode->next = head;
head = nextNode;
}
return head;
}
};