原題如下:
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) 把前半部分的鏈表和逆置後的鏈表“逐一”串起來,即可AC此題。
C++代碼如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseLinkList(ListNode* head){
if(!head && !head->next)
return head;
ListNode* first, *second, *temp;
first = head;
second = head->next;
while(second){
temp = second->next;
second->next = first;
first = second;
second = temp;
}
head->next = NULL;
return first;
}
void reorderList(ListNode* head) {
if(!head || !head->next){
return;
}
ListNode* slow, *fast;
slow = fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode* tail = reverseLinkList(slow);
ListNode* tempHead = head, *temp1, *temp2;
while(tempHead && tempHead->next && tail && tail->next){
temp1 = tempHead->next;
tempHead->next = tail;
temp2 = tail->next;
tail->next = temp1;
tempHead = temp1;
tail = temp2;
}
}
};