以下是用C语言编写的单链表示例代码:

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

// 定义节点结构体
typedef struct Node {
    int data;
    struct Node *next;
} Node;

// 初始化链表
Node *initList() {
    Node *head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    return head;
}

// 插入节点
void insertNode(Node *head, int data) {
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = head->next;
    head->next = newNode;
}

// 删除节点
void deleteNode(Node *head, int data) {
    Node *pre = head;
    Node *cur = head->next;
    while (cur != NULL) {
        if (cur->data == data) {
            pre->next = cur->next;
            free(cur);
            break;
        }
        pre = cur;
        cur = cur->next;
    }
}

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

// 测试
int main() {
    Node *head = initList();
    insertNode(head, 1);
    insertNode(head, 2);
    insertNode(head, 3);
    insertNode(head, 4);
    printf("初始链表:");
    printList(head);
    deleteNode(head, 2);
    printf("删除节点2后:");
    printList(head);
    return 0;
}

此单链表实现了初始化链表、插入节点、删除节点和打印链表等基本操作。可以根据需求进行修改和扩展

用c语言编写一个单链表

原文地址: http://www.cveoy.top/t/topic/cOyL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录