題幹
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}.
鏈表結構修改。要求in-place,不能使用輔助數據結構。
數據結構
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
解題思路
這個題有兩個思路:
1.兩個指針,第一個指針指示當前要添加結點的位置,第二個指針一直遍歷得到當前鏈表尾結點。將尾結點插入到當前結點後面。
2.三步走:
a.找到鏈表中間結點:用兩個指針遍歷,一個指針一次走一步,一個兩步。
b.反轉後半部分鏈表結點。
c.將後半部分結點插入前半部分結點。
參考代碼
方法一:
class Solution {
public:
void reorderList(ListNode *head) {
ListNode *cur=head;//當前結點
ListNode *tmp;
while(head!=NULL&&head->next!=NULL){
while(cur->next->next!=NULL){
cur=cur->next;
}
tmp=cur->next;//結點添加,畫一下就可以明白具體過程
cur->next=NULL;
tmp->next=head->next;
head->next=tmp;
head=cur=tmp->next;
}
}
};
方法二:
class Solution {
public:
void reorderList(ListNode *head) {
if (head==NULL||head->next==NULL)
return;
ListNode *p1=head,*p2=head;
//第一步:找到中間點
while(p2->next!=NULL&&p2->next->next!=NULL){
p1=p1->next;
p2=p2->next->next;
}
ListNode *tmp;
ListNode *mid=p1;
ListNode *pre_head=new ListNode(0);//建立僞頭,方便進行操作
pre_head->next=mid->next;
ListNode *cur=pre_head->next;
//第二步:反轉後半部分鏈表
while (cur->next!=NULL) {
ListNode *tmp=pre_head->next;
pre_head->next=cur->next;
cur->next=pre_head->next->next;
pre_head->next->next=tmp;
}
p1=head;
p2=pre_head->next;
//第三步:合併前後兩部分鏈表
while(p1!=mid){
mid->next=p2->next;
p2->next=p1->next;
p1->next=p2;
p1=p2->next;
p2=mid->next;
}
}
};
方法討論
根據代碼直觀可以得到,方法一代碼簡單但是算法複雜度較高爲O(n²),第二種方法代碼複雜但是算法複雜度比較低爲O(n)。
易錯點
邊界條件
找中間結點,反轉等處邊界條件。