#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node * prior;
struct node * next;
}NODE,*PNODE;
PNODE createList(PNODE);
void travelList(PNODE);
void insertList(PNODE,int,int);
int lengthList(PNODE);
void delList(PNODE,int,int *);
void main()
{
//头结点是需要造出来的,给他分配空间
PNODE phead=(PNODE)malloc(sizeof(NODE));
if(NULL==phead)
{
printf("内存分配失败");
exit(-1);
}
phead->next=NULL;
phead->prior=NULL;
//创建双链表
phead=createList(phead);
//遍历双链表
travelList(phead);
printf("\n");
//链表的插入
insertList(phead,2,3);
//遍历双链表
travelList(phead);
printf("\n");
printf("开始准备删除结点\n");
int val;
//链表结点删除
delList(phead,2,&val);
//遍历双链表
travelList(phead);
printf("\n");
}
PNODE createList(PNODE phead)
{
int len;
int val;
PNODE p=phead;
printf("请输入要初始化结点的个数:");
scanf("%d",&len);
for(int i=0;i<len;i++)
{
PNODE pnew=(PNODE)malloc(sizeof(NODE));
if(pnew==NULL)
{
printf("内存分配失败");
exit(-1);
}
printf("请输入给当前第%d个结点赋值",i+1);
scanf("%d",&val);
pnew->data=val;
pnew->prior=NULL;
pnew->next=NULL;
pnew->next=p->next;
pnew->prior=p;
p->next=pnew;
p=pnew;
}
return phead;
}
void delList(PNODE phead,int pos,int *val)
{
int i=0;
PNODE p=phead;
if(p==NULL||pos<1||pos>lengthList(phead))
{
printf("无法删除,删除不合法");
return;
}
while(i<pos-1)
{
p=p->next;
i++;
}
PNODE q=p->next;
*val=q->data;
printf("%d ",*val);
p->next=p->next->next;
p->next->prior=p;
free(q);
}
void travelList(PNODE phead)
{
PNODE pnew=phead->next;
while(pnew!=NULL)
{
printf("%d ",pnew->data);
pnew=pnew->next;
}
}
void insertList(PNODE phead,int pos,int val)
{
PNODE p=phead;
int i=0;
if(p==NULL||pos<1||pos>lengthList(phead))
{
printf("无法插入结点,不合法");
exit(-1);
}
while(i<pos-1)
{
p=p->next;
i++;
}
//初始化结点
PNODE pnew=(PNODE)malloc(sizeof(NODE));
pnew->data=val;
pnew->next=NULL;
pnew->prior=NULL;
//准备插入结点
pnew->next=p->next;
p->next->prior=pnew;
pnew->prior=p;
p->next=pnew;
}
int lengthList(PNODE phead)
{
PNODE pnew=phead;
int i=0;
while(pnew!=NULL)
{
pnew=pnew->next;
i++;
}
return i;
}
转载于:https://blog.51cto.com/1464490021/1864548