C language implements the classic data structure code---linked list

Linked List Introduction

A linked list is a common linear data structure that consists of a series of nodes, each node containing data and a pointer to the next node. The nodes in the linked list can be distributed discontinuously in the memory, and they are connected in series through pointers.

The realization principle of linked list

Node definition : first define a node structure, which contains two member variables: data and a pointer to the next node.

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

 Create a node : Through dynamic memory allocation, use malloc()a function to create a new node, and initialize data and pointers.

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

Insert node : To insert a node in the linked list, you need to find the previous node at the insertion position, then point the pointer of the new node to the next node of the previous node, and then point the pointer of the previous node to the new node.

void insertNode(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

Delete node : To delete a node in the linked list, you need to find the previous node of the node to be deleted, then point the pointer of the previous node to the next node of the node to be deleted, and finally release the memory of the node to be deleted.

void deleteNode(Node** head, int data) {
    Node* current = *head;
    Node* previous = NULL;
    while (current != NULL && current->data != data) {
        previous = current;
        current = current->next;
    }
    if (current == NULL) {
        return;
    }
    if (previous == NULL) {
        *head = current->next;
    } else {
        previous->next = current->next;
    }
    free(current);
}

Traversing the linked list : Traverse each node in the linked list in turn through the pointer, and output the data of the node.

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

Advantages of linked lists

The advantage of a linked list is that the time complexity of inserting and deleting nodes is O(1), without the need to move other elements like an array. But the disadvantage of the linked list is that accessing a certain node requires traversing the entire linked list, and the time complexity is O(n).

Guess you like

Origin blog.csdn.net/L888666Q/article/details/131414090