#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *prior,*next;
}LinkDoubleList;
//初始化双向链表
LinkDoubleList *InitList(LinkDoubleList *L)
{
L=(LinkDoubleList *)malloc(sizeof(LinkDoubleList));
L->prior=NULL;
L->next=NULL;
return L;
}
//插入操作(前插法)
int FrontInsItem(LinkDoubleList *L,int item,int pos)
{
int i=1;
LinkDoubleList *p=L;
LinkDoubleList *q=(LinkDoubleList *)malloc(sizeof(LinkDoubleList));
q->data=item;
if(pos<1)
{
printf("Position is error!\n");
return 0;
}
if(L->next==NULL)
{
if(pos==1)
{
L->next=q;
q->prior=L;
q->next=NULL;
return 1;
}
else
{
printf("List is empty,position is error!\n");
return 0;
}
}
while(p->next!=NULL&&i<pos)
{
p=p->next;
i++;
}
if(p->next==NULL)
{
printf("Node is not exist!\n");
return 0;
}
q->next=p->next;
p->next->prior=q;
p->next=q;
q->prior=p;
return 1;
}
//插入操作(后插法)
int RearInsItem(LinkDoubleList *L,int item,int pos)
{
LinkDoubleList *p=L;
LinkDoubleList *q=(LinkDoubleList *)malloc(sizeof(LinkDoubleList));
q->data=item;
int i=0;
if(pos<1)
{
printf("Position is error!\n");
return 0;
}
if(L->next==NULL)
{
if(pos==1)
{
L->next=q;
q->prior=L;
q->next=NULL;
return 1;
}
printf("Link is empty!\n");
return 0;
}
while(p!=NULL&&i<pos)
{
p=p->next;
i++;
}
if(p==NULL)
{
printf("Position is error!\n");
return 0;
}
q->next=p->next;
q->prior=p;
p->next=q;
if(p->next!=NULL)
{
p->next->prior=q;
}
return 1;
}
//删除操作
int DelItem(LinkDoubleList *L,int item)
{
if(L->next==NULL)
{
printf("List is empty!\n");
return 0;
}
LinkDoubleList *p=L->next;
while(p->next)
{
if(p->data==item)
{
p->next->prior=p->prior;
p->prior->next=p->next;
return 1;
}
p=p->next;
}
if(p->next==NULL)
{
if(p->data==item)
{
p->prior->next=NULL;
return 1;
}
printf("Item is not exist!\n");
return 0;
}
}
//遍历链表
int ListTraverse(LinkDoubleList *L)
{
LinkDoubleList *p=L->next;
if(L->next==NULL)
{
printf("List is empty!\n");
return 0;
}
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return 1;
}
int main()
{
LinkDoubleList *L;
L=InitList(L);
}
线性表(双向链表)
最新推荐文章于 2024-09-04 19:49:04 发布