利用C语言实现了一个简单的双向链表,功能有创建链表、插入节点、删除节点、判断链表是否为空。
编译器为gcc,gcc中要使用bool类型,需要添加头文件stdbool.h头文件,vc中则不需要。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Dulnode
{
int data;
struct Dulnode *prior ,*next;
}DulNode,*pNode;
pNode CreatDulList(void);
void TraverseList(pNode pHead);
bool InsertList(pNode pHead,int pos,int val);
bool DeleList(pNode pHead,int pos,int *pVal);
bool EmptyList(pNode pHead);
int main()
{
int val;
pNode pHead = NULL;
pHead = CreatDulList();
TraverseList(pHead);
if(true == InsertList(pHead,4,-10))
printf("元素插入成功!\n");
else
printf("插入失败!\n");
TraverseList(pHead);
if(true == DeleList(pHead,4,&val))
printf("元素删除成功,删除的元素为:%d\n",val);
else
printf("删除失败!\n");
TraverseList(pHead);
return 0;
}
pNode CreatDulList(void)
{
int val,len;
pNode pHead = (pNode)malloc(sizeof(DulNode));
if(NULL == pHead)
{
printf("动态内存分配失败,程序终止!\n");
exit(-1);
}
pHead->next = NULL;
pHead->prior = NULL;
pNode pTail = pHead;
printf("请输入需要生成链表节点的个数:len = \n");
scanf("%d",&len);
for(int i = 0;i < len;i++)
{
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
pNode pNew = (pNode)malloc(sizeof(DulNode));
if(NULL == pNew)
{
printf("内存分配失败,程序终止!\n");
exit(-1);
}
pNew ->data = val;
pNew ->next =NULL;
pNew ->prior = pTail;
pTail ->next = pNew;
pTail = pNew;
}
return pHead;
}
bool EmptyList(pNode pHead)
{
if(NULL == pHead->next)
return false;
else
return true;
}
void TraverseList(pNode pHead)
{
if(false == EmptyList(pHead))
{
printf("链表为空!\n");
exit(-1);
}
else
{
while( NULL != (pHead = pHead -> next))
printf(" %d ",pHead->data);
}
printf("\n");
}
bool InsertList(pNode pHead,int pos,int val)
{
pNode pTail = pHead;
for( int i = 0;i < pos;i++ )
{
if(NULL == (pTail = pTail->next))
{
printf("找不到要插入的点!\n");
return false;
}
}
pNode pInsert =(pNode)malloc(sizeof(DulNode));
if(NULL == pInsert)
{
printf("动态内存分配失败!\n");
exit(-1);
}
pInsert ->data = val;
pInsert ->next = pTail ->next;
pTail ->next ->prior = pInsert;
pTail ->next = pInsert;
pInsert ->prior = pTail;
return true;
}
bool DeleList(pNode pHead,int pos,int *pVal)
{
pNode pTail = pHead;
for( int i = 0;i <= pos;i++ )
{
if(NULL == (pTail = pTail->next))
{
printf("找不到要删除的点!\n");
return false;
}
}
pTail ->prior ->next = pTail ->next;
pTail ->next ->prior = pTail ->prior;
* pVal = pTail ->data;
free(pTail);
pTail = NULL;
return true;
}