双向链表
由于单向链表只适合"从前往后找",而"从后往前找"不是它的强项;所以引入双向链表:可以解决算法中需要大量地找某指定结点的前驱结点。
指针域:用于指向当前结点的直接前驱结点
数据域:用于存储数据元素
指针域:用于指向当前结点的直接后继结点
typedef struct line { struct line *perior; int data; struct line *next; }line;
1 双向链表的创建
双链表创建过程中,每创建一个新节点,都要与其前驱节点建立两次联系,分别是:1.将新节点的 prior 指针指向直接前驱节点;2.将直接前驱节点的 next 指针指向新节点;
#include <stdio.h> #include <stdlib.h> typedef struct line { struct line *perior; int data; struct line *next; }line; typedef struct line *Link; Link Creat_Line(Link Head) { int i; Link List,New; Head=(Link)malloc(sizeof(line)); Head->perior=NULL; Head->next=NULL; Head->data=1; List=Head; for(i=2;i<6;i++) { New=(Link)malloc(sizeof(line)); New->data=i; New->next=NULL; New->perior=NULL; List->next=New; New->perior=List; List=List->next; } return Head; } void Display(Link Head) { Link temp=Head; while(temp) { if(temp->next==NULL) { printf("%d\n",temp->data); } else { printf("%d\n",temp->data); } temp=temp->next; } } int main() { Link Head=NULL; Head=Creat_Line(Head); Display(Head); system("pause"); return 0; }
2 双向链表添加结点
2.1 添加至表头
假设新元素节点为temp,表头节点为 head,则需要做以下 2 步操作即可:1.temp->next=head;head->prior=temp;2.将 head移至temp重新指向新的表头;
2.2 添加至链表中间
1.新节点先与其直接后继节点建立双层逻辑关系;
2.新节点的直接前驱节点与之建立双层逻辑关系;
2.3 添加到链表尾部
1.找到双链表中最后一个节点;
2.让新节点与最后一个节点进行双层逻辑关系;
Link Insert(Link Head,int position,int d) { Link temp,New; int i; temp=(Link)malloc(sizeof(line)); temp->next=NULL; temp->perior=NULL; temp->data=d; if(position==0) //添加到链表表头 { temp->next=Head; Head->perior=temp; Head=temp; } else { New=Head; for(i=0;i<position-1;i++) { New=New->next; } if(New->next==NULL) //添加到链表尾部 { New->next=temp; temp->perior=New; } else { New->next->perior=temp; //添加到链表中间 temp->next=New->next; New->next=temp; temp->perior=New; } } return Head; }
3 删除指定数据
Link Delect(Link Head,int d) { Link temp=Head; while(temp) { if(temp->data==d) { temp->perior->next=temp->next; temp->next->perior=temp->perior; free(temp); return Head; } temp=temp->next; } return Head; }
4 双向循环链表的创建
#include <stdio.h> #include <stdlib.h> typedef struct Line { struct Line *perior; int data; struct Line *next; }Line; typedef struct Line *Link; Link Create_Line(Link Head) { int i; Link Temp,New; Head=(Link)malloc(sizeof(Line)); Head->data=5; Head->next=NULL; Head->perior=NULL; Temp=Head; for(i=14;i<17;i++) { New=(Link)malloc(sizeof(Line)); New->data=i; New->next=NULL; New->perior=NULL; Temp->next=New; New->perior=Temp; Temp=Temp->next; } Temp->next=Head; Head->perior=Temp; return Head; } void Display(Link Head) { Link temp=Head; while(temp->next!=Head) { if(temp->next!=NULL) printf("%d ",temp->data); else printf("%d ",temp->data); temp=temp->next; } printf("%d ",temp->data); } int main() { Link Head=NULL; Head=Create_Line(Head); Display(Head); system("pause"); return 0; }