实现循环双链表的操作及其实现
程序员文章站
2022-06-04 09:34:24
...
代码:
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef struct Node{
int data;
Node* pre;
Node* next;
}Node,*Linklist;
int getElem(Linklist L){
int x;
scanf("%d",&x);
int i=0;
Node* s;
while(s!=L&&i<x){
s=s->next;
i++;
}
return s->pre->data;
}
void InsertNode(Linklist &L){
int x;
scanf("%d",&x);
Node* s=(Node*)malloc(sizeof(Node));
Node* r;
r=L->next;
printf("L的前驱为:%d\n",L->pre->data);
if(x>L->pre->data){
r=L;
s->data=x;
s->pre=r->pre;
r->pre=s;
s->pre->next=s;
s->next=r;
printf("现在的L的前驱为:%d\n",L->pre->data);
}else{
while(r->next!=L&&x>r->data){
r=r->next;
}
s->data=x;
s->pre=r->pre;
s->next=r->pre->next;
r->pre->next=s;
r->pre=s;
}
}
void DeleteNode(Linklist &L){
int x;
scanf("%d",&x);
int i=0;
Node* s;
s=L->next;
while(i<x&&s->next!=L){
s=s->next;
i++;
}
s->pre->next=s->next;
delete(s);
}
void showLinklist(Linklist L){
Node* t;
t=L->next;
while(t!=L){
if(t->next!=L)
printf("%d->",t->data);
else
printf("%d\n",t->data);
t=t->next;
}
}
int main(){
int x;
scanf("%d",&x);
Node* s;
Node* r=(Node*)malloc(sizeof(Node));
Linklist L;
L=(Node*)malloc(sizeof(Node));
r=L;
s=L;
L->next=L;
L->pre=L;
int y;
for(int i=0;i<x;i++){
scanf("%d",&y);
s=(Node*)malloc(sizeof(Node));
s->data=y;
s->next=L;
L->pre=s;
r->next=s;
s->pre=r;
r=s;
}
printf("显示该循环链表的数据项:\n");
showLinklist(L);
printf("对该链表进行增删改查,其操作如下:\n");
printf("请插入一个元素:\n");
InsertNode(L);
printf("并执行此操作的结果显示如下:\n");
showLinklist(L);
printf("删除一个元素:\n");
DeleteNode(L);
printf("并执行该操作的结果显示如下:\n");
showLinklist(L);
printf("请执行获取某个元素的操作:\n");
int num=getElem(L); //获取索引为3的循环链表的元素
printf("查到由索引指向的元素:\n");
printf("该元素为:%d\n",num);
}
效果图: