如何使用C语言创建链表

链表的实现、搜索、移除、释放

  • 如下
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int num;
    struct node *next;
} Node;

typedef struct list
{
    Node *head;
    Node *tail;
} List;

void add(List *list, int num);
void print_linked_list(List *list);
int search(List *list, int num);
void delete(List *list, int num);
void freeList(List *list);

int main(int argc, char const *argv[])
{
    int num;
    List list;
    list.head = list.tail = NULL; // define a head pointer
    do
    {
        scanf("%d", &num);
        add(&list, num);
    } while (num != -1);

    delete(&list, 3);
    print_linked_list(&list);

    // if (search(&list, 3))
    // {
    //     printf("found\n");
    // }
    // else
    // {
    //     printf("not found\n");
    // }
    freeList(&list);

    return 0;
}

void add(List *pList, int num) // 传入的是head的指针,也就是二级指针,以便对head进行修改
{
    if (num != -1)
    {
        Node *p = (Node *)malloc(sizeof(Node)); // 在内存中分配一个链表大小的位置
        p->num = num;                           // initialize the node
        p->next = NULL;

        // find the last linked list
        if (pList->head)
        {
            // attach and reset the tail
            pList->tail = pList->tail->next = p;
        }
        else
        {
            // initialize the head and the tail
            pList->head = pList->tail = p;
        }
    }
    return;
}

void print_linked_list(List *list)
{
    Node *p;
    p = list->head; // rewind to head
    while (p)
    {
        printf("%d ", p->num);
        p = p->next;
    }
    return;
}

int search(List *list, int num)
{
    for (Node *p = list->head; p; p = p->next)
    {
        if (p->num == num)
        {
            return 1;
        }
    }
    printf("\n");
    return 0;
}

void delete(List *list, int num)
{
    // use *q to store the previous node
    for (Node *p = list->head, *q = NULL; p; q = p, p = p->next)
    {
        if (p->num == num)
        {
            if (q)
            {
                q->next = p->next;
                free(p);
            }
            else
            {
                list->head = p->next;
                free(p);
            }

            return;
        }
    }
}

void freeList(List *list)
{
    // 用q来保存p的下一个节点,防止p被释放后找不到下一个节点
    for (Node *p = list->head, *q; p; p = q)
    {
        q = p->next;
        free(p);
    }
}
posted @ 2025-09-21 10:38  Franksama  阅读(16)  评论(0)    收藏  举报