给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
基本思路:前半部分和后半部分逆序糅杂在一起,第一印象是用stack存储节点,然后在遍历一次穿插节点。
void reorderList(ListNode* head) {
stack<ListNode*> stk;
ListNode* cur=head;
int count=0;
while(cur){
stk.push(cur);
count++;
cur=cur->next;
}
cout<<count<<endl;
int num=count>>1;
ListNode *temp;
cur=head;
if(count&1){
for(int i=0;i<num;i++){
ListNode *l=stk.top();
stk.pop();
l->next=cur->next;
cur->next=l;
cur=cur->next->next;
}
cur->next=nullptr;
}
else{
cout<<num<<endl;
for(int i=0;i<num;i++){
ListNode *l=stk.top();
stk.pop();
l->next=(cur->next==l)?nullptr:cur->next;
cur->next=l;
cur=cur->next->next;
}
}
}
基本思路2:通过上述代码发现,整个链表,前面的从头开始,后部分是从尾部逆序开始,很容易让人想到双指针 。
void reorderList(ListNode* head) {
if(head==nullptr)
return ;
vector<ListNode*> data;
ListNode *cur=head;
while(cur){
data.emplace_back(cur);
cur=cur->next;
}
int i=0,j=data.size()-1;
while(i<j){
data[i]->next=data[j]; //这种分开的写法,还是用的很好的。
i++;
if(i==j) //偶数个节点时,会提前相遇的
break;
data[j]->next=data[i];
j--;
}
data[i]->next=nullptr;
}
基本思路3: 凡是可以用栈解决的,都可以用递归解决。
void reorderList(ListNode* head) {
if(head==nullptr||head->next==nullptr||head->next->next==nullptr){
return;
}
ListNode *cur=head;
int count=0;
while(cur){
count++;
cur=cur->next;
}
reorderListHelper(head,count);
}
ListNode *reorderListHelper(ListNode *head,int len){
if(len==1){
ListNode *outtail=head->next;
head->next=nullptr;
return outtail;
}
if(len==2){
ListNode *outtail=head->next->next;
head->next->next=nullptr;
return outtail;
}
ListNode *tail=reorderListHelper(head->next,len-2);
ListNode *outtail=tail->next;
ListNode *subHead=head->next;
head->next=tail;
tail->next=subHead;
return outtail;
}
基本思路4:用快慢指针将链表分为前后两部分,后半部分逆转链表。在穿插在一起。
void reorderList(ListNode* head) {
if(head==nullptr||head->next==nullptr||head->next->next==nullptr){
return;
}
ListNode *slow=head;
ListNode *fast=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
}
ListNode *newhead=slow->next;
slow->next=nullptr; //前半部分大于等后半部分长度
newhead=reverseList(newhead);//逆转后半部分链表
slow=head;
while(newhead){
ListNode *temp=newhead->next;
newhead->next=slow->next;
slow->next=newhead;
slow=slow->next->next;
newhead=temp;
}
}
ListNode *reverseList(ListNode *head){
if(head==nullptr||head->next==nullptr)
return head;
ListNode *tail=head;
head=head->next;
tail->next=nullptr;
while(head){
ListNode *temp=head->next;
head->next=tail;
tail=head;
head=temp;
}
return tail;
}