1. 程式人生 > >雙向循環鏈表的建立

雙向循環鏈表的建立

oid wid stdlib.h android tlist 元素 雙向 mage 結果

單鏈表的缺點是只能往前,不能後退,雖然有循環單鏈表,但後退的成本還是很高的,需要跑一圈。在這個時候呢,雙向鏈表就應運而生了,再加上循環即雙向循環 鏈表就更加不錯了。所謂雙向鏈表只不過是添加了一個指向前驅結點的指針,雙向循環鏈表是將最後一個結點的後繼指針指向頭結點,這在遍歷時很關鍵。

技術分享

程序:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct DuLNode{
int data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinkList;
//建立一個只含頭結點的空雙向循環鏈表
int InitList_DuL(DuLinkList &L){
L=(DuLinkList)malloc(sizeof(DuLNode));
if(!L){
exit(OVERFLOW);
}
L->prior=L;
L->next=L;
return OK;
}
//建立一個帶頭結點的含n個元素的雙向循環鏈表L
int CreateList_DuL(DuLinkList &L,int n){
DuLinkList p,q;
int i;
printf("Input the datas:");
q=L;
for(i=0;i<n;i++){
p=(DuLinkList)malloc(sizeof(DuLNode));
scanf("%d",&p->data);
p->next=q->next;//新元素總是插入表尾
q->next=p;
p->prior=q;
L->prior=p;//修改頭結點的prior的值,指向新結點p
q=p;//q指向新的尾結點
}
return OK;

}
//遍歷雙向循環鏈表
int TraverseList_DuL(DuLinkList L){
DuLinkList p;
p=L->next;//p指向第一個結點
  while(p!=L){//還沒到鏈表結尾 這地方註意如何還按照以前條件while(p)輸出將是無線循環,因為這是循環鏈表頭尾相連
printf("%d",p->data);
p=p->next;
}
return OK;
}
main(){
int n;
DuLinkList L;
InitList_DuL(L);
printf("Input the length of the list L:");
scanf("%d",&n);
CreateList_DuL(L,n);
printf("Output the datas:");
TraverseList_DuL(L);
printf("\n");
}
結果:
[email protected]

/* */:~/work/c/doublelianbiao$ ./createlist
Input the length of the list L:3
Input the datas: 1 3 5
Output the datas:135


雙向循環鏈表的建立