因爲單向鏈表只適合"從前日後找",而"從後往前找"不是它的強項;因此引入雙向鏈表:能夠解決算法中須要大量地找某指定結點的前驅結點。算法
指針域:用於指向當前結點的直接前驅結點spa
數據域:用於存儲數據元素指針
指針域:用於指向當前結點的直接後繼結點code
typedef struct line { struct line *perior; int data; struct line *next; }line;
1 雙向鏈表的建立blog
雙鏈表建立過程當中,每建立一個新節點,都要與其前驅節點創建兩次聯繫,分別是:1.將新節點的 prior 指針指向直接前驅節點;2.將直接前驅節點的 next 指針指向新節點;it
#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 雙向鏈表添加結點io
2.1 添加至表頭class
假設新元素節點爲temp,表頭節點爲 head,則須要作如下 2 步操做便可:1.temp->next=head;head->prior=temp;2.將 head移至temp從新指向新的表頭;List
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; }