双向循环链表的插入,删除的操作如图:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode *next;
struct LNode *prior;
}Node,*LinkList;
int createLinkList(LinkList &L,int length){
LinkList head,temp,hmove ;
L = (LinkList)malloc(sizeof(Node));
if(!L){
printf("malloc action error");
return 0;
}
L->next = L;
L->prior = L;
hmove = head = L;
int j=0;
for(;j<length;j++){
temp = (LinkList)malloc(sizeof(Node));
if(!temp){
printf("malloc action error");
return 0;
}
scanf("%d",&temp->data);
temp->next = head;
head->prior = temp;
temp->prior = hmove;
hmove->next = temp;
hmove = temp;
}
return 1;
}
int printLinkList(LinkList L){
LinkList head;
head = L;
head = head->next;
while(head!=L){
printf("%d ",head->data);
head = head->next;
}
return 1;
}
int insertLinkList(LinkList L,int i,int element){
LinkList head,temp;
head = L;
head = head->next;
int j = 0;
while(j<i-1){
++j;
head = head->next;
if(head == L){
break;
}
}
if(j<i-1){
printf("insert ERROR");
return 0;
}
temp = (LinkList)malloc(sizeof(Node));
if(!temp){
printf("malloc action error");
return 0;
}
temp->data = element;
temp->next = head->next;
temp->prior =head;
head->next = temp;
temp->next->prior = temp;
return 1;
}
int deleteLinkList(LinkList L,int i){
LinkList head;
int j =0;
head = L;
head = head->next;
while(j<i-1){
++j;
head = head->next;
if(head==L){
break;
}
}
if(j<i-1){
printf("insert ERROR");
return 0;
}
printf("%d\n",head->data);
head->prior->next = head->next;
head->next->prior = head->prior;
free(head);
return 1;
}
int main(){
LinkList L;
int length;
printf("create linkList\n");
scanf("%d",&length);
createLinkList(L,length);
printLinkList(L);
//
printf("\ninsert linkList\n");
int index,element;
scanf("%d%d",&index,&element);
insertLinkList(L,index,element);
printLinkList(L);
printf("\ndelete linkList\n");
scanf("%d",&index);
deleteLinkList(L,index);
printLinkList(L);
}