20170515_重新组装单链表
143. Reorder List
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}.
//143. Reorder List
// 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}.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(nullptr) {}
};
ListNode *CreatList(ListNode * &root, vector<int> &a)
{
int n=a.size();
if(n==0)
return root=nullptr;
else
{
root=new ListNode(a[0]);
ListNode *r=root;
for(int i=1; i<n; ++i)
{
ListNode *p=new ListNode(a[i]);
r->next=p;
r=p;
}
return root;
}
}
void OutList(ListNode *root)
{
if(root==nullptr)
return;
else
{
ListNode *p=root;
while(p != nullptr)
{
if(p->next != nullptr)
cout<<p->val<<",";
else
cout<<p->val;
p=p->next;
}
cout<<endl;
}
}
class Solution
{
public:
void reorderList(ListNode *head)
{
ListNode *root=head;
if(root == nullptr || root->next == nullptr || root->next->next == nullptr)
return; //单链表是空的、只有一个节点、只有两个节点时,直接返回!确保有三个节点时才进行操作。
ListNode *p=root;
ListNode *rear=root;
while(rear->next != nullptr) //rear已经指向最后一个节点
rear=rear->next;
ListNode *temp=new ListNode(0);
ListNode *q=temp,*rear2;
while(p != rear)
{
q->next=p;
p=p->next; //p指向下一个节点
rear2=p;
q=q->next;
q->next=rear;
q=q->next;
if(rear2 != rear && rear2->next != rear)
{
while(rear2->next != rear) //rear2已经指向倒数第二个节点
rear2=rear2->next;
rear2->next=nullptr; //断开与最后一个节点的连接
rear=rear2; //rear指向前一个节点
}
else
rear=rear2;
}
if(rear->next != nullptr) //奇数个节点时
{
q->next=rear;
q=q->next;
q->next=nullptr;
}
root=temp->next;
delete temp;
OutList(root);
}
};
int main()
{
vector<int> a;
int ch;
cout<<"依次输入单链表节点数据:"<<endl;
while(cin>>ch)
a.push_back(ch);
cin.clear();
cin.sync();
ListNode *r;
ListNode *root=CreatList(r,a);
cout<<"单链表建立完成."<<endl;
cout<<"顺序输出单链表:"<<endl;
OutList(root);
cout<<"顺序输出单链表完成."<<endl;
Solution example;
example.reorderList(root);
system("pause");
return 0;
}