要求:设双链表表示的线性表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;
}