- 1.双向循环链表的创建
- 2.双向循环链表的插入
- 3.双向循环链表的删除
- 4.遍历双向循环链表
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10010
#define ElemType int
typedef struct DuLNode{
ElemType data;
struct DuLNode *prior,*next;
}DuLNode,*DuLinkList;
//创建双向循环链表
DuLinkList CreateList(int n){
DuLinkList head=(DuLNode *)malloc(sizeof(DuLNode));
DuLinkList q=head;
head->next=NULL;
head->prior=NULL;
DuLNode *p;
while(n--){
int elem;
p=(DuLNode *)malloc(sizeof(DuLNode));
printf("输入:");
scanf("%d",&elem);
p->data=elem;
p->next=p;
p->prior=p;
q->next=p;
p->prior=q;
q=p;
}
p->next=head;
head->prior=p;
return head;
}
//双向循环链表指定位置插入(后插)
bool InsertElem(DuLNode *list1,int index,ElemType e){
DuLNode *p=(DuLNode *)malloc(sizeof(DuLNode));
p->data=e;
p->next=NULL;
p->prior=NULL;
DuLNode *head=list1;
DuLNode *h=head->next;
int count1=0;
while(h&&(h!=head)&&count1<index){
h=h->next;
count1++;
}
if(h&&count1==index){
p->next=h->next;
p->next->prior=p;
h->next=p;
p->prior=h;
}else
return false;
return true;
}
//双向循环链表删除指定值
bool DeleteElem(DuLNode *list1,ElemType e){
DuLNode *head=list1;
DuLNode *p=head->next;
while(p&&(p!=head)&&p->data!=e){
p=p->next;
}
if(p&&p->data==e){
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
}else
return false;
return true;
}
//双向循环链表遍历
void display(DuLNode *list1){
DuLNode *head=list1;
DuLNode *p=head->next;
while(p&&(p!=head)){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
//判断操作结果是否成功
void check(bool flag){
if(flag){
printf("操作成功!\n");
}else{
printf("操作失败!\n");
}
}
int main(){
int n;//链表结点数
int elem;
DuLinkList duList;
printf("创建双向链表\n");
printf("输入结点个数:");
scanf("%d",&n);
duList=CreateList(n);
while(1){
int op;
int index;
int elem;
bool flag;
printf("请选择操作\n1.指定位置之后插入\n2.删除指定值的元素\n3.打印\n");
scanf("%d",&op);
switch(op){
case 1:
scanf("%d %d",&index,&elem);
flag=InsertElem(duList,index,elem);
check(flag);
break;
case 2:
scanf("%d",&elem);
flag=DeleteElem(duList,elem);
check(flag);
break;
case 3:
display(duList);
break;
default:
break;
}
}
return 0;
}