温馨提示×

怎么用C语言创建单链表

小亿
83
2023-11-22 15:27:11
栏目: 编程语言

使用C语言创建单链表的基本步骤如下:

  1. 定义一个结构体来表示链表的节点,该结构体包含两个成员:数据域和指针域。
struct Node {
    int data;
    struct Node* next;
};
  1. 创建一个头节点,并将其指针域初始化为NULL。
struct Node* head = NULL;
  1. 定义一个函数来向链表中插入新节点。该函数接受一个整数作为参数,将其存储在新节点的数据域中,并将新节点插入到链表的末尾。
void insert(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    
    if (head == NULL) {
        head = newNode;
    } else {
        struct Node* current = head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}
  1. 定义一个函数来遍历并打印链表中的所有节点。
void printList() {
    struct Node* current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}
  1. 编写主函数,调用上述函数来创建、插入和打印链表。
int main() {
    insert(1);
    insert(2);
    insert(3);
    printList();
    
    return 0;
}

以上代码将创建一个包含3个节点的单链表,并输出节点的值。输出结果为:1 2 3。你可以在此基础上进一步扩展链表的功能,比如插入、删除和查找节点等操作。

0