线性表双链表实现
程序员文章站
2022-06-06 20:38:18
...
前言:
其实链表最核心的地方就是链的问题,只要把一种搞明白,后面的就不那么难了(刚开始接触链表怎么也不明白,想的多了,用的劲多了,也就慢慢理解了)
双链表的代码可以直接运行,显示出效果,代码用C语言写的,有什么问题可以评论留言,看到会回复
效果图:
#include <stdio.h>
#include <malloc.h>
typedef int ElemType;
typedef struct DLink{
ElemType data; //数据域
struct DLink *before,*next; //前驱和后继指针
}DLink,*DLinkList;
/*创建一个双向链表*/
DLinkList InitDLink(DLink *dl)
{
dl = (DLinkList)malloc(sizeof(DLink));
DLinkList newnode,oldnode=dl;
int i = 1;
while(i<=10)
{
newnode = (DLinkList)malloc(sizeof(DLink));
oldnode->next=newnode; //前驱指针
newnode->before=oldnode; //后继指针
newnode->data=i;
oldnode=newnode;
i++;
}
oldnode->next=NULL;
return dl;
}
/*求双向链表的长度*/
int LenghtDLink(DLink *dl)
{
DLinkList LinkLenght = dl->next;
int lenght = 0;
while(LinkLenght)
{
LinkLenght = LinkLenght->next;
lenght++;
}
return lenght;
}
/*双向链表插入操作*/
DLinkList InsertDLink(DLink *dl,int i,ElemType e)
{
DLinkList newnode,oldnode=dl;
int j = 1;
while(oldnode && j<i)
{
oldnode = oldnode->next;
j++;
}
if(!oldnode || j>i)
return dl;
newnode = (DLinkList)malloc(sizeof(DLink)); //生成新结点
newnode->data = e;
newnode->next = oldnode->next;
oldnode->next = newnode;
newnode->before = oldnode;
return dl;
}
/*双向链表删除操作*/
DLinkList DeleteDLink(DLink *dl,int i)
{
int lenght = LenghtDLink(dl);
if(i<1||i>lenght)
return dl;
int j = 1;
DLinkList deletenode=dl;
while(deletenode && j<i)
{
deletenode = deletenode->next;
j++;
}
deletenode->next = deletenode->next->next;
deletenode->next->next->before = deletenode->next->before;
return dl;
}
int main(void)
{
DLink Initdl,Insertdl,Deletedl,*Initlink,*Insertlink,*Deletelink;
Initlink = InitDLink(&Initdl);
printf("插入数据前,双向链表长度:%d\n",LenghtDLink(Initlink));
Initlink = Initlink->next;
while(Initlink)
{
printf("前驱指针域:%p\t数据域:%d\t后继指针域:%p\n",Initlink->before,Initlink->data,Initlink->next);
Initlink = Initlink->next;
}
printf("\n");
Insertlink = InitDLink(&Insertdl);
int address = 6;
Insertlink = InsertDLink(Insertlink,address,666);
printf("插入数据后,双向链表长度:%d\n",LenghtDLink(Insertlink));
Deletelink = Insertlink;
Insertlink = Insertlink->next;
while(Insertlink)
{
printf("前驱指针域:%p\t数据域:%d\t后继指针域:%p\n",Insertlink->before,Insertlink->data,Insertlink->next);
Insertlink = Insertlink->next;
}
printf("\n");
Deletelink = DeleteDLink(Deletelink,address);
printf("删除数据后,双向链表长度:%d\n",LenghtDLink(Deletelink));
Deletelink = Deletelink->next;
while(Deletelink)
{
printf("前驱指针域:%p\t数据域:%d\t后继指针域:%p\n",Deletelink->before,Deletelink->data,Deletelink->next);
Deletelink = Deletelink->next;
}
return 0;
}