溫馨提示×

c語言怎么編寫一個(gè)簡單的單鏈表

小億
86
2024-01-13 14:12:32
欄目: 編程語言

以下是一個(gè)簡單的單鏈表的C語言實(shí)現(xiàn):

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

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

// 創(chuàng)建鏈表節(jié)點(diǎn)
struct ListNode* createNode(int value) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = value;
    newNode->next = NULL;
    return newNode;
}

// 插入節(jié)點(diǎn)到鏈表尾部
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;
    }
}

// 刪除指定值的節(jié)點(diǎn)
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) { // 刪除頭節(jié)點(diǎn)
                *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;

    // 插入節(jié)點(diǎn)
    insert(&head, 1);
    insert(&head, 2);
    insert(&head, 3);

    // 打印鏈表
    printList(head);

    // 刪除節(jié)點(diǎn)
    removeNode(&head, 2);

    // 打印鏈表
    printList(head);

    return 0;
}

該代碼實(shí)現(xiàn)了一個(gè)簡單的單鏈表,包括創(chuàng)建節(jié)點(diǎn)、插入節(jié)點(diǎn)、刪除節(jié)點(diǎn)以及打印鏈表的功能。在main()函數(shù)中演示了如何使用這些功能。

0