1. 程式人生 > >雙向連結串列的基本操作

雙向連結串列的基本操作

雙向連結串列與單鏈表的最大區別就是可逆。

插入(頭插)

刪除

具體程式碼如下:

DeLink.h

typedef int ELEM_TYPE;

typedef struct DNode
{
	ELEM_TYPE data;
	struct DNode* next;
	struct DNode* perv;	
}DNode,*PDNode;

void Init(PDNode sl);
DNode* BuyNode(ELEM_TYPE val);
bool InsertHead(PDNode sl,ELEM_TYPE val);
void Show(PDNode sl);
bool InsertTail(PDNode sl,ELEM_TYPE val);
bool DeleteKey(PDNode sl,ELEM_TYPE val);
void clear(PDNode sl);
void destory(PDNode sl);

DeLink.cpp

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>

#include "DeLink.h"

/*初始化*/
void Init(PDNode sl)
{
	if(sl == NULL)
	{
		return ;
	}
	sl->next = NULL;
	sl->perv = NULL;
}


/*申請新的節點*/
DNode* BuyNode(ELEM_TYPE val)
{
	DNode* pnewnode = (DNode*)malloc(sizeof(DNode));
	if(pnewnode == NULL) exit(0);
	pnewnode->data = val;
	pnewnode->next = NULL;
	pnewnode->perv = NULL;
	return pnewnode;
}

/*頭插*/
bool InsertHead(PDNode sl,ELEM_TYPE val)
{
	if(sl == NULL)
	{
		return false;
	}
	
	DNode* pnewnode = BuyNode(val);
	pnewnode->next = sl->next;
	pnewnode->perv = sl;
	sl->next = pnewnode;
	if(sl->next != NULL)
	{
		sl->next->perv = pnewnode;
	}
	return true;
}

/*尾插*/
bool InsertTail(PDNode sl,ELEM_TYPE val)
{
	if(sl == NULL)
	{
		return false;
	}
	
	DNode* pCur = sl;
	while(pCur->next != NULL)
	{
		pCur = pCur->next;
	}
	
	DNode* pnewnode = BuyNode(val);
	pCur->next = pnewnode;
	pnewnode->perv = pCur;
	return true;
}

/*刪除*/
bool DeleteKey(PDNode sl,ELEM_TYPE val)
{
	if(sl == NULL)
	{
		return false;
	}
	DNode *pCur = sl->next;
	while(pCur != NULL)
	{
		if(pCur->data == val)
		{
			break;
		}
		pCur = pCur->next;
	}
	
	pCur->perv->next = pCur->next;
	if(pCur->next != NULL)
	{
		pCur->next->perv = pCur->perv;
	}
	free(pCur);
	
	return true;
}

void Show(PDNode sl)
{
	if(sl == NULL)
	{
		return;
	}
	DNode* pCur = sl->next;
	while(pCur != NULL)
	{
		printf("%d ",pCur->data);
		pCur = pCur->next;
	}
}

void clear(PDNode sl)
{
	DNode* pCur = sl->next;
	DNode* pNext = pCur;
	while(pCur != NULL)
	{
		pNext = pCur->next;
		free(pCur);
		pCur = pNext;
	}
	sl->next = NULL;
}

void destory(PDNode sl)
{
	clear(sl);
}

main.cpp

#include <stdio.h>

#include "DeLink.h"

int main()
{
	DNode sl;
	Init(&sl);
	/*for(int i = 0; i < 5; i++)
	{
		InsertHead(&sl,i+1);
	}*/
	for(int i = 0; i < 5; i++)
	{
		InsertTail(&sl,i+1);
	}
	DeleteKey(&sl,3);
	Show(&sl);
	clear(&sl);
	destory(&sl);
}