//双链表的初始化,建立,插入,查找,删除。 //
//Author:Zyw //
//Date: 2013.11.22 //
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *pNext;
struct Node *pPrior;
}Node, *pNode;
/*创建双链表*/
pNode CreateDulLink()
{
pNode head,tmp,body;
ElemType tmpElem;
head = new Node;
head->pNext = NULL;
body = head;
cout<<"Please input a num"<<endl;
cin>>tmpElem;
while(0 != tmpElem)
{
tmp = new Node;
tmp->data = tmpElem;
tmp->pPrior = body;
tmp->pNext = body->pNext;
body->pNext = tmp;
body = tmp;
cout<<"Please input a num"<<endl;
cin>>tmpElem;
}
body->pNext = NULL;
return head;
}
/*删除节点*/
pNode DeleteNode(pNode head, ElemType num)
{
pNode body;
body = head;
//找到要删除的节点
while((NULL != body->pNext) && (num != body->data))
{
body = body->pNext;
}
if (num == body->data)
{
if (head == body)
{
head = head->pNext;
head->pPrior = NULL;
}
else if (NULL != body->pNext)
{
body->pPrior->pNext = body->pNext;
body->pNext->pPrior = body->pPrior;
}
else
{
body->pPrior->pNext = NULL;
}
free(body);
}
else
{
cout<<"Can't find the node!"<<endl;
}
return head;
}
/*插入节点*/
pNode InsertNode(pNode head, int location, ElemType num)
{
pNode tmp,body;
int nodeLen,tmpNum;
tmp = head;
for (nodeLen = 0; NULL != tmp->pNext; nodeLen++)
{
tmp = tmp->pNext;
}
if ((location < 0)||(location > nodeLen))
{
cout<<"Error insert location!"<<endl;
}
tmp = head;
body = new Node;
if (0 == location)
{
body->data = num;
body->pNext = tmp;
body->pPrior = NULL;
head = body;
}
else if ((0 < location) && (location < nodeLen))
{
for (tmpNum = 0; tmpNum < location; tmpNum++)
{
tmp = tmp->pNext;
}
body->data = num;
body->pNext = tmp->pPrior->pNext;
tmp->pPrior->pNext = body;
body->pPrior = tmp->pPrior;
tmp->pPrior = body;
}
else
{
while(NULL != tmp->pNext)
{
tmp = tmp->pNext;
}
body->data = num;
body->pNext = NULL;
tmp->pNext = body;
body->pPrior = tmp;
}
return head;
}
/*显示链表*/
int ShowDulNode(pNode head)
{
pNode tmp = head->pNext;
//正向输出
while (tmp->pNext)
{
cout<<tmp->data<<endl;
tmp = tmp->pNext;
}
cout<<tmp->data<<endl;//输出最后一个数
//反向输出
while (head != tmp)
{
cout<<tmp->data<<endl;
tmp = tmp->pPrior;
}
return 0;
}
int main(int argc, char ** argv)
{
pNode dulLink;
dulLink = CreateDulLink();
ShowDulNode(dulLink);
InsertNode(dulLink,3,3);
ShowDulNode(dulLink);
DeleteNode(dulLink,3);
ShowDulNode(dulLink);
return 0;
}
双向链表的建立插入删除
最新推荐文章于 2022-08-21 20:21:48 发布