双向链表C语言语法实现

438 阅读2分钟

双向链表

与单向链表不同,双向链表不但有后继还有前驱。但是和单向链表一样的地方是带有头结点的双向链表在插入删除元素时更方便。

双向链表的C语言代码实现

首先创建双向链表的节点构造体:

#include <stdio.h>
#include "stdlib.h"
#include "math.h"
#include "time.h"

#define MAXSIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

typedef int ElemType;
typedef int Status;

typedef struct Node {
    ElemType data;
    struct Node *prior;
    struct Node *next;
}Node;

typedef struct Node *BinaryLinkList;

1.创建双向链表

Status CreateLinkList(BinaryLinkList *L){
    *L  = (BinaryLinkList)malloc(sizeof(Node));
    if(*L == NULL) return ERROR;

    (*L)->data = NULL;
    (*L)->prior = NULL;
    (*L)->next = NULL;

    BinaryLinkList p = *L;
    for(int i=1; i<=10; i++) {
        BinaryLinkList temp = (BinaryLinkList)malloc(sizeof(Node));
        if(temp == NULL) return ERROR;
        temp->next = NULL;
        temp->data = i;

        p->next = temp;
        temp->prior = p;
        p = temp;
    }

    return OK;
}
  1. 遍历双向链表中的所有元素
void show(BinaryLinkList L) {
    BinaryLinkList temp = L->next;
    if (temp == NULL){
        printf("this binary linklist is empty\n");
        return;
    }

    while(temp){
        printf("%d ", temp->data);
        temp = temp->next;
    }

    printf("\n");
}
  1. 插入元素到指定位置
Status ListInsert(BinaryLinkList *L, int index, ElemType e) {

    if(index < 1) return ERROR;

    BinaryLinkList temp, target;
    int i;
    for(target = *L, i=1; target != NULL, i<index; target=target->next, i++);
    if(target == NULL) return ERROR;
    temp = (BinaryLinkList)malloc(sizeof(Node));
    temp->data = e;
    temp->next = NULL;
    if(target->next != NULL) {
       temp->next = target->next;
       target->next->prior = temp;
    }
    target->next = temp;
    temp->prior = target;

    return OK;
}
  1. 删除指定位置上的元素
Status DeleteElementInLinkList(BinaryLinkList *L, int index, ElemType *e){

    BinaryLinkList temp = *L;
    if(temp == NULL || index < 1) return ERROR;

    int i = 1;
    while(i<index && temp != NULL){
        i++;
        temp = temp->next;
    }

    if(temp->next == NULL) return ERROR;
    BinaryLinkList target = temp->next;
    if (target->next != NULL) {
        target->next->prior = temp;
    }
    *e = target->data;
    temp->next = target->next;
    free(target);

    return OK;
}
  1. 删除指定值的元素
Status DeleteElementWithValue(BinaryLinkList *L, ElemType value){
    BinaryLinkList temp = *L;
    while(temp){
        if (temp->data == value){
            temp->prior->next = temp->next;
            if(temp->next != NULL){
                temp->next->prior = temp->prior;
            }
            free(temp);
            return OK;
        }
        temp = temp->next;
    }
    return ERROR;
}