数据结构第一次试验:双向循环链表
前言
为了帮助同学们完成痛苦的实验课程设计,本作者将其作出的实验结果及代码贴至优快云中,供同学们学习参考。如有不足或描述不完善之处,敬请各位指出,欢迎各位的斧正!
一、实验内容
第53页第2题第9小题
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,写出算法change(p)交换p所指向的结点及其前驱结点的顺序。
二、实验环境
Dev C++或Visual Studio 2019
三、实验目的
1.掌握用顺序表实现线性表的存储。
2.掌握顺序表的常规操作
3.掌握双向循环链表的建立
4.掌握双向循环链表中两个紧临结点的交换
四、算法设计
void exchange(Node* p)
{
Node* q=p->prior;
q->prior->next=p;
p->prior=q->prior;
q->next=p->next;
q->prior=p;
p->next->prior=q;
p->next=q;
}
其实这个地方用画图更容易理解一些
其中红色指prior,蓝色指next
第一步q->prior->next=p;
第二步p->prior=q->prior;
第三步q->next=p->next;
第四步q->prior=p;
第五步p->next->prior=q;
第六步p->next=q;
至此即可完成双向循环链表中两个临位的交换
五、实验代码
为方便检查,在main函数中建立长度为10的双向循环链表
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next = NULL;
Node* prior = NULL;
Node(){}
Node(int d)
{
this->data=d;
}
};
struct LinkList
{
Node header;
int length=0;
Node* tail=header.next;
void insert(int a)
{
Node* nNode=new Node(a);
if(tail==NULL)
{
tail=nNode;
nNode->next=NULL;
}
else
{
tail->next=nNode;
nNode->prior=tail;
nNode->next=header.next;
header.next->prior=nNode;
}
header.next=nNode;
length++;
}
void output() //this function is used for checking the sequence
{
Node* p=header.next;
while (p->next!=header.next)
{
cout<<p->data<<"=";
p=p->next;
}
cout<<p->data<<endl;
}
void exchange(Node* p) //this function is used for exchange those two nodes
{
Node* q=p->prior;
q->prior->next=p;
p->prior=q->prior;
q->next=p->next;
q->prior=p;
p->next->prior=q;
p->next=q;
}
};
int main()
{
LinkList list;
int n=10; // n means the number of nodes which used for construct the list &&int only
int a=10; // a means the number of node which exchanges
/*cin>>n;
if(n<=1)cout<<"NUMBERS ERROR!";*/
for(int i=1;i<=n;i++)
list.insert(i);
Node* p=list.header.next;
/*cin>>a;
if(a>n)cout<<"NUMBERS ERROR!"*/
for(int i=1;i<=11-a;i++)
p=p->next;
list.exchange(p);
list.output();
return 0;
}
六、实验结果截图
为方便检查,在main函数中建立长度为10的双向循环链表
若p指向第四个结点,则输出如下
(双向循环链表,1与10也相连)
若p指向第一个结点,则输出如下
(双向循环链表,2与10也相连)
若p指向最后一个结点(第十个),则输出如下
(双向循环链表,9与10也相连)
七、实验分析(选做)
时间复杂度:O(n)
空间复杂度:O(n)