目录
结构体
typedef int DataType;
typedef struct node
{
struct node *pPre;
DataType data;
struct node *pNext;
}LinkNode;
创建链表
LinkNode *CreateDouList()
{
LinkNode *pHead=NULL;
pHead=malloc(sizeof(LinkNode));
if(pHead==NULL)
{
return NULL;
}
pHead->pPre=NULL;
pHead->pNext=NULL;
return pHead;
}
插入链表
头插法
int HeadInsertDouList(LinkNode *pHead,DataType Tmpdata)
{
//申请新节点
LinkNode *pNewNode=NULL;
pNewNode=malloc(sizeof(LinkNode));
if(pNewNode==NULL)
{
return 0;
}
//为新节点数据项赋值
pNewNode->data=Tmpdata;
//新节点pnext指向原来的第一个节点
pNewNode->pNext=pHead->pNext;
//新节点的pre指向头结点
pNewNode->pPre=pHead;
//头节点的pnext指向新节点
pHead->pNext=pNewNode;
//链表不为空时,后一个节点的pre指向新节点
if(pNewNode->pNext!=NULL)
{
pNewNode->pNext->pPre=pNewNode;
}
return 0;
}
尾插法
int TailInsertDouList(LinkNode *pHead,DataType Tmpdata)
{
LinkNode *pNewNode=NULL;
LinkNode *pTmpNode=NULL;
pNewNode=malloc(sizeof(LinkNode));
if(pNewNode==NULL)
{
return 0;
}
pTmpNode=pHead;
while(pTmpNode->pNext!=NULL)
{
pTmpNode=pTmpNode->pNext;
}
pNewNode->data=Tmpdata;
pNewNode->pNext=NULL;
pNewNode->pPre=pTmpNode;
pTmpNode->pNext=pNewNode;
return 0;
}
遍历打印
int ShowDouList(LinkNode *pHead)
{
LinkNode *pTmpNode=NULL;
pTmpNode=pHead->pNext;
while(pTmpNode!=NULL)
{
printf("%d ",pTmpNode->data);
pTmpNode=pTmpNode->pNext;
}
return 0;
}
删除
//删除
int DeleteDouList(LinkNode *pHead,DataType Tmpdata)
{
LinkNode *pTmpNode=NULL;
LinkNode *pNextNode=NULL;
pTmpNode=pHead->pNext;
while(pTmpNode!=NULL)
{
if(pTmpNode->data==Tmpdata)
{
pNextNode = pTmpNode->pNext;
pTmpNode->pPre->pNext=pTmpNode->pNext;
if(pTmpNode->pNext!=NULL)
{
pTmpNode->pNext->pPre=pTmpNode->pPre;
}
free(pTmpNode);
}
pTmpNode=pNextNode;
//pTmpNode=pTmpNode->pNext;虽然pTmpNode被释放,但是堆区里面的内容如果没有被重新分配,数据就还存在,此时可以访问到但是属于非法访问
}
return 0;
}
更新
int UpdateDouList(LinkNode *pHead,DataType OldData,DataType NewData)
{
LinkNode *pTmpNode=NULL;
pTmpNode=pHead->pNext;
while(pTmpNode!=NULL)
{
if(pTmpNode->data==OldData)
{
pTmpNode->data=NewData;
}
pTmpNode=pTmpNode->pNext;
}
return 0;
}
查找
LinkNode *FindDouList(LinkNode *pHead,DataType data)
{
LinkNode *pTmpNode=NULL;
pTmpNode=pHead->pNext;
while(pTmpNode!=NULL)
{
if(pTmpNode->data==data)
{
return pTmpNode;
}
pTmpNode=pTmpNode->pNext;
}
}
销毁
//销毁
int DestroyDouList(LinkNode **pHead)
{
LinkNode *pTmpNode=NULL;
LinkNode *pTmpNext=NULL;
pTmpNode=*pHead;
while(pTmpNode!=NULL)
{
pTmpNext=pTmpNode->pNext;
free(pTmpNode);
pTmpNode=pTmpNext;
}
*pHead=NULL;
}
标签:pTmpNode,pNewNode,NULL,链表,pHead,双向,数据结构,LinkNode,pNext
From: https://blog.csdn.net/m0_64378221/article/details/141686214