双链表改造

要求:设双链表表示的线性表L=(a1,a2…an),试写一段时间复杂度为O(n)的算法,将L改造为L=(a1,a3,…an,…a4,a2)。

//第7题

#include<iostream>
using namespace std;
struct Node {
	Node(int x)
	{
		value = x;
		before = NULL;
		next = NULL;
	}
	int value;
	Node* before;
	Node* next;
};

void Change(Node* a)
{
	Node *phead = a, *p = a->next, *temp = NULL;
	while (p->before != phead && p->next != phead)
	{
		p->before->next = p->next;
		p->next->before = p->before;
		temp = p;
		p = p->next->next;
		phead->before->next = temp;
		temp->next = phead;
		temp->before = phead->before;
		phead->before = temp;
		phead = phead->before;
	} 
}

int main()
{
	//由题目可得n>=3,先建立双向链表
	int initValue, count, iValue;
	cin >> initValue >> count;
	Node* ha = new Node(initValue); //建立初始值
	Node* p = ha;
	for (int i = 2; i <= count; i++) //通过for循环,建立双向链表。 count表示双向链表中元素个数
	{
		cin >> iValue;
		Node* t = new Node(iValue);
		p->next = t;
		t->before = p;
		p = t;
	}
	p->next = ha;
	ha->before = p;
	cout << "改造前:";
	p = ha;
	while (p->next != ha) {
		cout << p->value << " ";
		p = p->next;
	}
	cout << p->value << endl;
	Change(ha);
	cout << "改造后:";
	p = ha;
	while (p->next != ha) {
		cout << p->value << " ";
		p = p->next;
	}
	cout << p->value << endl;
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值