1. 程式人生 > 其它 >關於線性表中雙鏈表的實現方式

關於線性表中雙鏈表的實現方式

資料結構四

一、關於線性表中雙鏈表

#include "stdio.h"
#include "stdlib.h"

struct DNode{
    int data;
    struct DNode* prior,* next;
};
struct DNode* CreateNode(int e){
    struct DNode* p=(struct DNode*) malloc(sizeof(struct DNode));
    if(!p){
        printf("No enough memory to allocate!\n");
        exit(0);
    }
    p->data=e;
    p->prior=NULL;
    p->next=NULL;
    return p;
}
//在p節點之後插入節點s
int InsertNextDNode(struct DNode* p,struct DNode* s){
    if(p==NULL||s==NULL) return 0;
    s->next=p->next;
    if(p->next!=NULL)
        p->next->prior=s;
    s->prior=p;
    p->next=s;
    return 1;
}
//在p節點之後刪除後繼節點
int DeleteNextDNode(struct DNode* p){
    struct DNode* q=NULL;
    if(p==NULL) return 0;
    q=p->next;//找到p節點的後繼節點
    p->next=q->next;
    if(q->next!=NULL)
        q->next->prior=p;
    free(q);
    return 1;
}
//遍歷雙鏈表
void ListDisplay(struct DNode* L){
    struct DNode* p=L;
    int j=0;
    while (p!=NULL){
        printf("The %dth node of Double-linked-list is %d\n",j,p->data);
        j++;
        p=p->next;
    }
}
//銷燬雙鏈表
void DestroyList(struct DNode* L){
    while (L->next!=NULL){
        DeleteNextDNode(L);
    }
    free(L);
}
int main(){
    struct DNode* p=NULL,*s=NULL;
    //1.建立頭指標,指向頭節點
    struct DNode* L= CreateNode(0);//建立帶頭節點的雙鏈表
    //2.迴圈遍歷插入5個數據
    p=L;
    for (int i = 0; i < 5; i++) {
        s= CreateNode(i*500+1);
        InsertNextDNode(p,s);
        p=p->next;
    }
    ListDisplay(L);
    DestroyList(L);
    return 0;
}

實現結果:

D:\project\clion\ch1\cmake-build-debug\other_linked_list.exe
The 0th node of Double-linked-list is 0
The 1th node of Double-linked-list is 1
The 2th node of Double-linked-list is 501
The 3th node of Double-linked-list is 1001
The 4th node of Double-linked-list is 1501
The 5th node of Double-linked-list is 2001

Process finished with exit code 0