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

   2025-02-05 3320
核心提示:以下是一个简单的单链表的C语言实现:#include stdio.h#include stdlib.hstruct ListNode {int val;struct ListNode* next;};//

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言