温馨提示×

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

小亿
84
2024-01-13 14:12:32
栏目: 编程语言

以下是一个简单的单链表的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()函数中演示了如何使用这些功能。

0