C语言实现链表的创建和增删查改

为了进入3G实验室,经过一个晚自习的奋斗,实现了链表的常用功能
包括五个

  1. 创建

  2. 欢迎大家来学习,如果有空的话,我可以解释一下代码
#include <stdio.h>
#include <stdlib.h>
// 结构体,表示一个链表节点
typedef struct list_node
{
    int data;
    struct list_node *next;
} node;
// 链表创建函数,输入一个链表节点数
node *create(int n)
{
    node *head, *end, *p;
    head = (node *)malloc(sizeof(node));
    end = head;
    for (int i = 1; i <= n; i++)
    {
        p = (node *)malloc(sizeof(node));
        printf("please input the data\n");
        scanf("%d", &p->data);
        end->next = p;
        end = p;
    }
    end->next = NULL;
    return head;
}
// 链表打印函数,输入一个head指针
void print(node *p)
{
    while (p->next != NULL)
    {
        p = p->next;
        printf("%d\n", p->data);
    }
}
// 链表的增
void insert(node *p, int n, int data)
{
    node *t = p, *in;
    int i = 0;
    while (i < (n - 1) && t != NULL)
    {
        t = t->next;
        i++;
    }
    if (t != NULL)
    {
        in = (node *)malloc(sizeof(node));
        in->data = data;
        in->next = t->next;
        t->next = in;
    }
}

// 链表的删
void del(node *p, int n)
{
    node *t = p, *in;
    int i = 0;
    while (i < n && t != NULL)
    {
        in = t;
        t = t->next;
        i++;
    }
    if (t != NULL)
    {
        in->next = t->next;
        free(t);
    }
}
// 链表的查
int search(node *p, int data)
{
    int n = 0;
    p = p->next;
    while (p != NULL)
    {
        n++;
        if ((p->data) == data)
            return n;
        p = p->next;
    }
    printf("can not find");
}
// 链表的改
void change(node *p, int n, int data)
{
    p = p->next;
    for (int i = 1; i < n && p != NULL; i++)
    {
        p = p->next;
    }
    if (p == NULL)
    {
        printf("WA");
    }
    else
    {
        p->data = data;
    }
}
int main()
{
    // 创建
    printf("input the number of nodes,please\n");
    int n;
    scanf("%d", &n);
    node *p = create(n);
    // 增
    printf("insert\n");
    insert(p, 2, 520);
    print(p);
    // 删
    printf("del\n");
    del(p, 2);
    print(p);
    // 改
    printf("change\n");
    change(p, 1, 520);
    print(p);
    // 查
    printf("search\n");
    search(p, 520);
    printf("%d\n", search(p, 520));
}

posted @ 2023-09-21 20:57  加零lan  阅读(126)  评论(0编辑  收藏  举报