20170515_重新组装单链表

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值