新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言双向链表如何建立,c语言双向链表实现

发布时间:2023-12-01 22:27:34

c语言双向链表如何建立

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

  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⑸,直到完成所有节点的添加。

完全的示例代码以下:

#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.
");
        return;
    }
    printf("Nodes in the doubly linked list: 
");
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("
");
}

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