结构体使用
#include<stdio.h>
#include<malloc.h>
# include <stdlib.h>
typedef struct doublenode
{
int data;
struct doublenode*prior;
struct doublenode*next;
}Doublenode,*pDoublenode;
创建双链表
pDoublenode initdoublenode()
{
int len,i,val;
pDoublenode phead =(pDoublenode)malloc(sizeof(Doublenode));
phead ->prior=NULL;phead->next=NULL;phead->data=0;
pDoublenode temp=phead;
if (NULL == phead)
{
printf("分配失败, 程序终止!\n");
exit(-1);
}
printf("请输入您需要生成的链表节点的个数: len = ");
scanf("%d", &len);
for(i=0;i<len;i++)
{
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
pDoublenode pNew =(pDoublenode)malloc(sizeof(Doublenode));
pNew->prior=NULL;pNew->next=NULL;
if (NULL == pNew)
{
printf("分配失败, 程序终止!\n");
exit(-1);
}
pNew->data=val;
temp->next=pNew;
pNew->prior=phead;
temp=pNew;
pNew->next=NULL;
}
return phead;
}
遍历双链表
void traverse(pDoublenode phead)
{
pDoublenode temp=phead->next;
while (temp)
{
if (temp->next == NULL)
{
printf("%d\n", temp->data);
}
else
{
printf("%d <-> ", temp->data);
}
temp = temp->next;
}
}
删除某个元素
pDoublenode delete(pDoublenode head, int data)
{
pDoublenode temp = head;
while (temp)
{
if (temp->data == data)
{
temp->prior->next = temp->next;
temp->next->prior = temp->prior;
free(temp);
return head;
}
temp = temp->next;
}
printf("链表中无该数据元素\n");
return head;