温馨提示×

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

小亿
147
2023-12-27 14:30:22
栏目: 编程语言

在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。

0