头文件
#ifndef __DOULIST_H__
#define __DOULIST_H__
#include<stdio.h>
#include<stdlib.h>
/*存放数据类型*/
typedef int DataType;
/*存放节点类型*/
typedef struct node
{
DataType Data; //数据
struct node *pPre; //前一个节点指针
struct node *pNext; //后一个节点指针
}LinkNode;
#endif
创建双向链表
LinkNode *CreateDouList(void)
{
LinkNode *pTmpNode = NULL;
pTmpNode = malloc(sizeof(LinkNode));
if(NULL == pTmpNode)
{
return NULL;
}
pTmpNode->pPre = pTmpNode->pNext = NULL;
return pTmpNode;
}
插入链表
/*插入链表——头插法*/
int HeadInsertDouList(LinkNode *pHead,DataType TmpData)
{
LinkNode *pTmpNode = NULL;
pTmpNode = malloc(sizeof(LinkNode));
if(NULL == pTmpNode)
{
return -1;
}
pTmpNode->Data = TmpData;
pTmpNode->pNext = pHead->pNext;
pTmpNode->pPre = pHead;
pHead->pNext = pTmpNode;
if(pTmpNode->pNext != NULL)
{
pTmpNode->pNext->pPre = pTmpNode;
}
return 0;
}
/*插入链表——尾插法*/
int TailInsertDouList(LinkNode *pHead,DataType TmpData)
{
LinkNode *pTmpNode = NULL;
LinkNode *pNewNode =NULL;
pNewNode = pHead;
if(pNewNode->pNext != NULL)
{
pNewNode = pNewNode->pNext;
}
pTmpNode = malloc(sizeof(LinkNode));
if(NULL == pTmpNode)
{
return -1;
}
pTmpNode->Data = TmpData;
pTmpNode->pNext = NULL;
pTmpNode->pPre = pNewNode;
pNewNode->pNext = pTmpNode;
return 0;
}
遍历打印双向链表
/*遍历打印双向链表——正向*/
int FrontShowDouList(LinkNode *pHead)
{
LinkNode *pTmpNode = NULL;
pTmpNode = pHead->pNext;
if(NULL == pTmpNode)
{
return -1;
}
//遍历
while(pTmpNode != NULL)
{
printf("%d \n",pTmpNode->Data); //打印
pTmpNode = pTmpNode->pNext;
}
printf("\n");
return 0;
}
/*遍历打印双向链表——反向*/
int BehindShowDouList(LinkNode *pHead)
{
LinkNode *pTmpNode = NULL;
//遍历
pTmpNode = pHead;
while(pTmpNode->pNext != NULL)
{
pTmpNode = pTmpNode->pNext; //指针遍历到末尾
}
while(pTmpNode != pHead)
{
printf("%d \n",pTmpNode->Data); //打印
pTmpNode = pTmpNode->pPre; //指针向前一节点遍历
}
printf("\n");
return 0;
}
删除链表节点
/*删除双向链表节点*/
int DeleteDouList(LinkNode *pHead, DataType TmpData)
{
LinkNode *pTmpNode = NULL;
LinkNode *pNextNode = NULL;
int cnt = 0;
pTmpNode = pHead->pNext;
while(pTmpNode->Data)
{
if(pTmpNode->Data == TmpData)
{
pNextNode = pTmpNode->pNext;
pTmpNode->pPre->pNext = pNextNode;
if(pTmpNode->pNext !=NULL)
{
pTmpNode->pNext->pPre = pTmpNode->pPre;
}
free(pTmpNode);
pTmpNode = pNextNode;
cnt++;
}
else
{
pTmpNode = pTmpNode->pNext;
}
}
return cnt;
}
销毁链表
/*销毁双向链表*/
int DestroyDouList(LinkNode **ppHead)
{
LinkNode *pTmpNode = NULL;
LinkNode *pFreeNode = NULL;
pTmpNode = *ppHead;
pFreeNode = *ppHead;
while (pTmpNode != NULL)
{
pTmpNode = pTmpNode->pNext;
free(pFreeNode);
pFreeNode = pTmpNode;
}
*ppHead = NULL;
return 0;
}