1.5 双向链表

虽然使用单链表能 100% 解决逻辑关系为 "一对一" 数据的存储问题,但单链表更适合 "从前往后" 找,而 "从后往前" 找并不是它的强项。

为了能够高效率解决类似的问题,引入双向链表。

#include "stdafx.h"

typedef struct line {
    struct line * prior;
    int data;
    struct line * next;
}line;

line * initLine(line *head) {
    head = (line*)malloc(sizeof(line));
    head->prior = NULL;
    head->next = NULL;
    head->data = 1;

    line * list = head;
    for (int i = 2; i <= 5; i++) {
        line * body = (line*)malloc(sizeof(line));
        body->prior = NULL;
        body->next = NULL;
        body->data = i;

        list->next = body;
        body->prior = list;
        list = list->next;
    }
    return head;
}

void display(line *head) {
    line * temp = head;
    while (temp) {
        if (temp->next == NULL)
            printf("%d\n", temp->data);
        else {
            printf("%d <-> ", temp->data);
        }
        temp = temp->next;
    }
}

line * insertLine(line * head, int data, int add) {
    line *temp = (line*)malloc(sizeof(line));
    temp->data = data;
    temp->prior = NULL;
    temp->next = NULL;
    if (add = 1) {
        temp->next = head;
        head->prior = temp;
        head = temp;
    }
    else {
        line *body = head;
        for (int i = 1; i < add; i++) {
            body = body->next;
        }
        if (body->next == NULL) {
            body->next = temp;
            temp->prior = body;
        }
        else {
            body->next->prior = temp;
            temp->next = body->next;
            body->next = temp;
            temp->prior = body;
        }
    }
    return head;
}

line * deletLine(line* head, int data) {
    line *temp = head;
    while (temp) {
        if (temp->data == data) {
            temp->prior->next = temp->next;
            temp->next->prior = temp->prior;
            free(temp);
            return head;
        }
        temp = temp->next;
    }
    printf("Could not find data '%d'", data);
    return head;
}

int selectElem(line * head, int elem) {
    line * temp = head;
    int i = 1;
    while (temp) {
        if (temp->data == elem) {
            return i;
        }
        i++;
        temp = temp->next;
    }
    return -1;
}

line * updateElem(line *head, int add, int newElem) {
    line * temp = head;
    for (int i = 1; i < add; i++) {
        temp = temp->next;
    }
    temp->data = newElem;
    return head;
}

int main() {
    line *head = NULL;
    head = initLine(head);
    display(head);

    // 在表中第 3 的位置插入元素 7
    head = insertLine(head, 7, 3);
    display(head);
    //表中删除元素 2
    head = deletLine(head, 2);
    display(head);
    printf("元素 3 的位置是:%d\n", selectElem(head, 3));
    //表中第 3 个节点中的数据改为存储 6
    head = updateElem(head, 3, 6);
    display(head);
    return 0;
}

你可能感兴趣的:(1.5 双向链表)