双链表操作,图解

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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值