c语言怎么编写一个简单的单链表

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

以下是一个简单的单链表的C语言实现:

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

struct ListNode {
    int val;
    struct ListNode* next;
};

// 创建链表节点
struct ListNode* createNode(int value) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = value;
    newNode->next = NULL;
    return newNode;
}

// 插入节点到链表尾部
void insert(struct ListNode** head, int value) {
    struct ListNode* newNode = createNode(value);
    if (*head == NULL) {
        *head = newNode;
    } else {
        struct ListNode* cur = *head;
        while (cur->next != NULL) {
            cur = cur->next;
        }
        cur->next = newNode;
    }
}

// 删除指定值的节点
void removeNode(struct ListNode** head, int value) {
    struct ListNode* cur = *head;
    struct ListNode* prev = NULL;
    while (cur != NULL) {
        if (cur->val == value) {
            if (prev == NULL) { // 删除头节点
                *head = cur->next;
            } else {
                prev->next = cur->next;
            }
            free(cur);
            return;
        }
        prev = cur;
        cur = cur->next;
    }
}

// 打印链表
void printList(struct ListNode* head) {
    struct ListNode* cur = head;
    while (cur != NULL) {
        printf("%d ", cur->val);
        cur = cur->next;
    }
    printf("\n");
}

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

    // 插入节点
    insert(&head, 1);
    insert(&head, 2);
    insert(&head, 3);

    // 打印链表
    printList(head);

    // 删除节点
    removeNode(&head, 2);

    // 打印链表
    printList(head);

    return 0;
}

该代码实现了一个简单的单链表,包括创建节点、插入节点、删除节点以及打印链表的功能。在main()函数中演示了如何使用这些功能。

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

推荐阅读: c语言数组如何增加元素