雙向循環鏈表的建立


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

程序:

#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");
}
結果:
android@android-Latitude-E4300:~/work/c/doublelianbiao$ ./createlist
Input the length of the list L:3
Input the datas: 1 3 5
Output the datas:135


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM