第二章算法设计题9
题目描述
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,写出算法change(p),交换p所指向的结点及其前驱结点的顺序。
求解思路
代码实现
#pragma once
#include <iostream>
#include<string>
using namespace std;
typedef struct DuLnode
{
int data;
struct DuLnode* prior;
struct DuLnode* next;
}DuLnode,*DuLinkList;
void InitDuList(DuLinkList& DL)
{
DL = new DuLnode;
DL->next = DL;
DL->prior = DL;
}
void createDuLinklist(DuLinkList&DL,int n)
{
DuLnode* s;
DuLnode* p = DL;
for (int i = 0; i < n; i++)
{
s = new DuLnode;
if (!s)
{
cout << "内存分配失败" << endl;
exit(1);
}
cout << "请输入第" << i+1 << "个数据" << endl;
cin >> s->data;
p->next = s;
s->prior = p;
s->next = DL;
p = s;
}
}
void show_DuList(DuLinkList& DL)
{
DuLnode *p=DL->next;
while (p != DL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void Change(DuLnode *p)
{
DuLnode* q;
q = p->prior;
q->prior->next = p;
p->prior = q->prior;
q->next = p->next;
p->next->prior = q;
q->prior = p;
p->next = q;
}
int main()
{
DuLinkList DL;
InitDuList(DL);
createDuLinklist(DL, 4);
cout << "交换之前:" << endl;
show_DuList(DL);
cout << string(30, '*') << endl;
DuLnode* s;
s = new DuLnode;
cout << "请输入要交换的结点的值:" << endl;
cin>>s->data;
DuLnode* p;
p = DL->next;
while (p != DL)
{
if (p->data == s->data)
{
Change(p);
break;
}
else
{
p = p->next;
}
}
cout << "交换之后:" << endl;
show_DuList(DL);
system("pause");
return 0;
}
运行结果