c语言双向链表怎么建立

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

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

定义一个结构体表示链表的节点:
struct Node {    int data;    struct Node* prev;    struct Node* next;};
定义一个指向链表头部和尾部的指针:
struct Node* head = NULL;struct Node* tail = NULL;
创建一个新节点并赋值:
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;}
注意更新新节点和尾部节点的指针。重复步骤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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言