3.4 双链表

3.4 双链表_哔哩哔哩_bilibili

 

// 双链表(带头结点) C++编译
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef struct DNode{ //定义双链表结点类型
    int data;
    struct DNode *prev,*next; //前驱,后继指针
}DNode, *DLinkList;
 
//初始化双链表
bool InitDLinkList(DLinkList &L){
    L=(DNode*)malloc(sizeof(DNode));
    L->prev=NULL;
    L->next=NULL;
    return true;
}

//结点a之后插入结点b
bool InsertNextDNode(DNode *a, DNode *b){
    if(!a || !b) return false;
    b->prev=a;
    b->next=a->next;
    if(a->next) a->next->prev=b;
    a->next=b;
    return true;
}

//尾插法建立双链表
bool CreateDLinkList(DLinkList &L, int n, int s[]){
    if(!L || n<0 || !s) return false;
    DLinkList p,q;
    p=L; //p指向头结点
    for(int i=0; i<n; i++){
        q=(DNode*)malloc(sizeof(DNode));
        q->data=s[i];
        InsertNextDNode(p,q);
        p=p->next;
    }
    return true;   
}

//删除p结点的后继结点
bool DeletNextDNode(DNode *p){
    if(!p) return false; //不合法
    DNode *q=p->next;
    if(!q) return false; //不存在
    p->next=q->next;
    if(q->next) q->next->prev=p;
    free(q);
    return true;
}

//销毁一个双链表
bool DestoryList(DLinkList &L){
    while(L->next){
        DeletNextDNode(L);
    }
    free(L);
    L=NULL;  
}

//遍历输出单链表
bool ListOut(DLinkList L){
    if(!L) return false;
    DNode *p=L->next;
    while(p){
        printf("%d ",p->data); 
        p=p->next;
    }
    puts("");
}

int main(){
    DLinkList L;
    InitDLinkList(L);
    
    int n=3; int s[]={5,2,0};
    CreateDLinkList(L,n,s);
    ListOut(L);
    
    DeletNextDNode(L);
    ListOut(L);

    CreateDLinkList(L,n,s);
    ListOut(L);   
    return 0;
}

 

 

.

posted @ 2026-09-06 06:28  董晓  阅读(19)  评论(0)    收藏  举报