数据结构考研复习(双链表)

相较于单链表而言双链表更易于访问前驱结点,其余内容相差并不是很大,我在写这部分内容时基本上也还是套用之前写单链表的代码:

https://www.cnblogs.com/hortz/p/15085147.html

双链表的基本代码如下:

#include<stdio.h>
#include<malloc.h>

typedef struct DNode{
    int data;
    struct DNode *prior, *next;
}DNode, *DLinkList;

/* -1- 建立双链表(单链表的尾插法)*/
DLinkList Insert_List(DLinkList &D){
    int x;
    D = (DLinkList)malloc(sizeof(DNode));
    DNode *temp,*t = D;//t为表尾指针
    D->prior = NULL;
    D->next = NULL;
    while(x != 9999){
        scanf("%d",&x);
        temp = (DNode*)malloc(sizeof(DNode));
        temp->data = x;
        t->next = temp;
        temp->prior = t;//可省略
        t = temp;
    }
    return D;
}

/* -2- 获取元素*/
int Get_Element(DLinkList &D){
    DNode *temp = D->next;
    while(temp && temp->data!=9999){
        printf("%d  ",temp->data);
        temp = temp->next;
    }
    printf("\n");
}


/* -3- 插入结点*/
DLinkList Insert_Element(DLinkList &D,int i,int e){
    DNode *previous = D;
    int m =0;
    while(previous && m < i){
        previous= previous->next;
        m++;
    }
    DNode *temp = (DLinkList)malloc(sizeof(DNode));
    temp->data = e;

    temp->next = previous->next;//1
    previous->next->prior = temp;//2
    temp->prior = previous;//3
    previous->next = temp;//4
    //只要逻辑无误可以对上述语句进行删减或者交换顺序

    return D;
}


/* -4- 删除结点*/
DLinkList Delete_Element(DLinkList &D,int i){
    DNode *previous = D;
    int m = 0;
    while(previous && m < (i-1)){
        previous= previous->next;
        m++;
    }
    DNode *del_element = previous->next;
    previous->next = del_element->next;
    del_element->next->prior = previous;
    free(del_element);//释放结点空间
}




int main(){
    DLinkList D;

    printf("请依次输入数据:\n");
    printf("===================\n");
    Insert_List(D);
    Get_Element(D);
    int flag;
    printf("请进行选择:\n");
    printf("==1.在指定序列后插入元素==\n");
    printf("==2.双链表删除元素==\n");
    scanf("%d",&flag);
    switch(flag){
    case(1):
        {
            printf("请输入要插入元素的序列:\n");
            int m;
            scanf("%d",&m);
            printf("请输入要插入的元素值:\n");
            int e;
            scanf("%d",&e);
            Insert_Element(D,m,e);
            Get_Element(D);
            break;
        }
    case(2):
        {
            printf("请输入要删除的元素序列:\n");
            int m;
            scanf("%d",&m);
            Delete_Element(D,m);
            Get_Element(D);
            break;
        }

    }

    return 0;

}

 

 

 

posted on 2021-08-01 20:51  HOr7z  阅读(57)  评论(0编辑  收藏  举报