1、双链表与单链表相比,优缺点
双链表可以向前后方向查找,单链表只能向后查找
可以从任意一节点进行查找,单链表只能从头进行查找
2、图解,借鉴别人的
(1)、新建
(2)、添加 删除
3、实现
#include <iostream>
using namespace std;
#define MAXSIZE 64
struct Node{
char mdata[MAXSIZE];
Node *pproir;
Node *pnext;
};
Node *pHead = NULL;
Node *pTail = NULL;
/*
1、新建节点,设置proir=null,pnext=null
2、让头节点head和tail节点指向该新建节点
*/
Node *CreateDoubleLink(Node *phead,char *pdata)
{
if (!phead)
{
phead = new Node;
strcpy(phead->mdata,pdata);
phead->pnext =NULL;
phead->pproir = NULL;
}
return phead;
}
/*
尾插法
1、新建节点,让proir指向tail节点,pnext=null
2、tail指向该节点
*/
Node *AddDoubleNode(Node *phead,Node *ptail,char *pdata)
{
if (!pHead||!pTail) return NULL;
Node *ptemp = new Node;
strcpy(ptemp->mdata,pdata);
pTail->pnext = ptemp;
ptemp->pproir = ptail;
ptemp->pnext = NULL;
pTail = ptemp;
return phead;
}
/*
1、定义一个临时指针ptemp,指向phead,循环ptemp=ptemp->pnext
*/
void OutPrintLink(Node *phead,Node *ptail)
{
if (!phead||!ptail) return ;
Node *ptemp = phead;
while(ptemp ){
printf("节点名称为:%s\n",ptemp->mdata);
ptemp=ptemp->pnext;
}
}
/*
假设在A--B之间插入节点c
1、新建节点c,前后节点指向NULL
2、让c->pnext指向B,
3、让c->pproir指向A
4、让B->pproir指向C
5、让A->pnext指向C
*/
Node *InsertLinkNode(Node *phead,const char *pnews,const char *pnode)
{
if (!phead) return NULL;
Node *pnew = new Node;
strcpy(pnew->mdata,pnews);
pnew->pnext = NULL;
pnew->pproir = NULL;
Node *ptemp = phead;
while(1 && ptemp)
{
if (!strcmp(ptemp->mdata,pnode))
{
pnew->pnext = ptemp->pnext;
pnew->pproir = ptemp;
ptemp->pnext->pproir = pnew;
ptemp->pnext = pnew;
break;
}
ptemp = ptemp->pnext;
}
return phead;
}
/*
1、查找该节点ptemp,
2、该节点前节点的后指针,指向该节点的后节点
3、该节点后节点的前指针,指向该节点的前节点
4、删除该节点,释放该空间
*/
Node *DeleteLinkNode(Node *phead,const char *pnode)
{
if (!phead) return NULL;
Node *ptemp = phead;
while(1 && ptemp)
{
if (!strcmp(ptemp->mdata,pnode))
{
ptemp->pproir->pnext = ptemp->pnext;
ptemp->pnext->pproir = ptemp->pproir;
delete ptemp;
break;
}
ptemp = ptemp->pnext;
}
return phead;
}
int main()
{
char name[MAXSIZE]={0};
if(pHead = CreateDoubleLink(pHead,"head"))
{
pTail = pHead;
}
printf("请输入节点名字:");
gets(name);
while (1)
{
if (!strlen(name)) break;
pHead = AddDoubleNode(pHead,pTail,name);
memset(name,0,sizeof(name));
printf("请输入节点名字:");
gets(name);
}
printf("\n");
printf("插入新节点前:\n");
OutPrintLink(pHead,pTail);
printf("\n");
printf("插入新节点后:\n");
InsertLinkNode(pHead,"temp","3");
OutPrintLink(pHead,pTail);
printf("\n");
printf("删除节点后:\n");
DeleteLinkNode(pHead,"4");
OutPrintLink(pHead,pTail);
return 0;
}