温馨提示×

c语言双向链表怎么建立

小亿
92
2023-12-01 22:27:34
栏目: 编程语言

要建立一个双向链表,需要定义一个包含两个指针(指向前一个节点和后一个节点)和数据的结构体。然后按照以下步骤进行建立:

  1. 定义一个结构体表示链表的节点:
    struct Node {
        int data;
        struct Node* prev;
        struct Node* next;
    };
    
  2. 定义一个指向链表头部和尾部的指针:
    struct Node* head = NULL;
    struct Node* tail = NULL;
    
  3. 创建一个新节点并赋值:
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->prev = NULL;
    newNode->next = NULL;
    
  4. 如果链表为空,则将新节点设为头部和尾部:
    if (head == NULL) {
        head = newNode;
        tail = newNode;
    }
    
  5. 如果链表不为空,则将新节点添加到尾部:
    else {
        tail->next = newNode;
        newNode->prev = tail;
        tail = newNode;
    }
    
    注意更新新节点和尾部节点的指针。
  6. 重复步骤3-5,直到完成所有节点的添加。

完整的示例代码如下:

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* prev;
    struct Node* next;
};

void insert(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->prev = NULL;
    newNode->next = NULL;
    
    if (head == NULL) {
        head = newNode;
        tail = newNode;
    }
    else {
        tail->next = newNode;
        newNode->prev = tail;
        tail = newNode;
    }
}

void display() {
    struct Node* current = head;
    if (head == NULL) {
        printf("List is empty.\n");
        return;
    }
    printf("Nodes in the doubly linked list: \n");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    head = NULL;
    tail = NULL;
    
    insert(1);
    insert(2);
    insert(3);
    
    display();
    
    return 0;
}

这个示例代码创建了一个包含三个节点(1,2,3)的双向链表,并打印出节点的值。输出结果为:Nodes in the doubly linked list: 1 2 3

0