双链表(带头节点)按位序差插入数据

本文介绍了如何使用C++实现双链表,并重点讲解了按位序差插入数据的方法,通过示例代码展示具体操作过程。
摘要由CSDN通过智能技术生成
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
typedef struct DNode{
    ElemType data;
    struct DNode *next,*prior;
}DNode,*DLinkList;

bool InitDLinkList(DLinkList &L){
    L=(DNode *)malloc(sizeof(DNode));
    if(L==NULL)
        return false;
    L->next=NULL;
    L->prior=NULL;
}

bool EmptyDLinkList(DLinkList &L){
    if(L->next==NULL)
        printf("空表\n");
    else
        printf("非空表\n");
}

bool HeadInsertDLinkList(DLinkList &L){
    int x;
    scanf("%d",&x);
    while(x!=9999){
        DNode *p=(DNode *)malloc(sizeof(DNode));
        p->data=x;
        if(L->next==NULL){
            p->next=NULL;
            p->prior=L;
            L->next=p;
        }
        else{
            p->next=L->next;
            L->next->prior=p;
            p->prior=L;
            L->next=p;
        }
        scanf("%d",&x);
    }
    return L;
}

void PrintDLinkList(DLinkList &L){
    printf("链表为:");
    int i=0;
    DNode *p=(DNode*)malloc(sizeof(DNode));
    p=L;
    while(p->next!=NULL){
        p=p->next;
        i++;
        printf("[%d]%d[%d]<=>",p->prior,p->data,p->next);
    }
    printf("\n链表长度为:%d\n",i);
    if(p==NULL)
        printf("链表为空,无法输出");
}

bool InsertDLinkList(DLinkList &L,ElemType i,ElemType e){
    if(i<1){
        printf("输入的位序不合法\n");
        return false;
    }
    int j=0;
    DNode *p=(DNode*)malloc(sizeof(DNode));
    p=L;
    while(p!=NULL&&j<i-1){
        p=p->next;
        j++;
    }
    if(p==NULL){
        printf("指定位序节点为空,无法插入\n");
        return false;
    }
    DNode *s=(DNode*)malloc(sizeof(DNode));
    s->data=e;
    s->next=p->next;
    p->next->prior=s;
    s->prior=p;
    p->next=s;
    return true;
}

int main(){
    DLinkList L;
    InitDLinkList(L);
    EmptyDLinkList(L);
    HeadInsertDLinkList(L);
    EmptyDLinkList(L);
    PrintDLinkList(L);
    InsertDLinkList(L,3,88);
    PrintDLinkList(L);
}

运行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值