《数据结构-C语言实现链表(Linked List)》

链表(Linked List)是一种基本的数据结构,用于存储和组织数据。与数组不同,链表中的元素(节点)是通过指针相互链接的。每个节点包含一个数据元素和一个指向下一个节点的指针。

C语言中可以使用结构体来实现链表。下面是一个简单的示例代码:

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

struct Node {
    int data;
    struct Node *next;
};

typedef struct Node Node;

void add(Node **head, int data) {
    Node *new_node = (Node*)malloc(sizeof(Node));
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
}

void delete(Node **head, int data) {
    Node *current = *head;
    Node *previous = NULL;

    while (current != NULL && current->data != data) {
        previous = current;
        current = current->next;
    }

    if (current == NULL) {
        printf("Element not found\n");
        return;
    }

    if (previous == NULL) {
        *head = current->next;
    } else {
        previous->next = current->next;
    }

    free(current);
}

void print_list(Node *head) {
    Node *current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    Node *head = NULL;

    add(&head, 1);
    add(&head, 2);
    add(&head, 3);
    add(&head, 4);
    add(&head, 5);

    print_list(head); // Output: 5 4 3 2 1

    delete(&head, 3);

    print_list(head); // Output: 5 4 2 1

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Like_Bamboo/article/details/129674759
今日推荐