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 || !head->next) return;
int len = 0;
ListNode* end2 = head;
while (end2->next){ //计算长度
len++;
end2 = end2->next;
}
len = len/ 2; //分离
ListNode *head2 = head;
while (len){
head2 = head2->next;
len--;
}
ListNode* end1 = head2;
head2 = head2->next;
end1->next = nullptr;
ListNode* cur = head2; //后半段反序
ListNode* nex = cur->next;
head2->next = nullptr;
while (nex){
cur = nex;
nex = nex->next;
cur->next = head2;
head2 = cur;
}
ListNode* list1 = head; //排列
ListNode* next1 = list1->next;
ListNode* list2 = head2;
ListNode* next2 = list2->next;
while (list1&&list2){
list1->next = list2;
list2->next = next1;
list1 = next1;
list2 = next2;
if (next1)
next1 = next1->next;
if (next2)
next2 = next2->next;
}
return;
}
};