c语言链表添加节点的方法是什么

1581
2023/12/4 14:30:22
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,链表添加节点的方法是通过以下步骤进行的:

  1. 定义一个结构体来表示节点,该结构体包含一个数据成员和一个指向下一个节点的指针成员。例如:
struct Node {
    int data;
    struct Node* next;
};
  1. 创建一个新节点,并为新节点分配内存。例如:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  1. 设置新节点的数据值。例如:
newNode->data = 10;
  1. 将新节点的next指针指向链表的头节点。例如:
newNode->next = head;
  1. 将新节点设置为链表的新头节点。例如:
head = newNode;

完整的示例代码如下所示:

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

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

void insert(struct Node** head, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = *head;
    *head = newNode;
}

void printList(struct Node* head) {
    struct Node* temp = head;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main() {
    struct Node* head = NULL;

    insert(&head, 10);
    insert(&head, 20);
    insert(&head, 30);

    printList(head);

    return 0;
}

此代码将创建一个包含值为10、20和30的节点的链表,并打印出链表的内容:30 20 10。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言数组求和代码怎么写