美文网首页
c语言插入删除链表

c语言插入删除链表

作者: 一路向后 | 来源:发表于2021-04-25 22:46 被阅读0次

1.题目描述

输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。

链表的值不能重复。

构造过程,例如输入一行数据为:
6 2 1 2 3 2 5 1 4 5 7 2 2
则第一个参数6表示输入总共6个节点,第二个参数2表示头节点值为2,剩下的2个一组表示第2个节点值后面插入第1个节点值,为以下表示:
1 2 表示为
2->1
链表为2->1

3 2表示为
2->3
链表为2->3->1

5 1表示为
1->5
链表为2->3->1->5

4 5表示为
5->4
链表为2->3->1->5->4

7 2表示为
2->7
链表为2->7->3->1->5->4

最后的链表的顺序为 2 7 3 1 5 4

最后一个参数为2,表示要删掉节点为2的值
删除 结点 2

则结果为 7 3 1 5 4

链表长度不大于1000,每个节点的值不大于10000。
测试用例保证输入合法

2.源码实现

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

struct node {
    int val;
    struct node *next;
};

void insert_first(struct node *root, int v)
{
    struct node *p;

    root->next = (struct node *)malloc(sizeof(struct node));

    p = root->next;

    p->val = v;
    p->next = NULL;
}

void insert(struct node *root, int v, int u)
{
    struct node *p;
    struct node *q;

    p = root->next;

    while(p != NULL)
    {
        if(p->val == u)
        {
            q = (struct node *)malloc(sizeof(struct node));
            q->val = v;
            q->next = p->next;
            p->next = q;
        }

        p = p->next;
    }
}

void delete(struct node *root, int u)
{
    struct node *p;
    struct node *q;

    p = root->next;
    q = root;

    while(p != NULL)
    {
        if(p->val == u)
        {
            q->next = p->next;
            free(p);
        }

        q = q->next;
        p = p->next;
    }
}

void freelist(struct node *root)
{
    struct node *p;
    struct node *q;

    p = root->next;

    while(p != NULL)
    {
        q = p->next;
        free(p);
        p = q;
    }
}

int main()
{
    struct node *root = (struct node *)malloc(sizeof(struct node));
    struct node *p;
    int u, v;
    int n;
    int i;

    while(scanf("%d", &n) != EOF)
    {
        if(n <= 0)
        {
            continue;
        }

        scanf("%d", &v);

        insert_first(root, v);

        for(i=1; i<n; i++)
        {
            scanf("%d %d", &v, &u);

            insert(root, v, u);
        }

        scanf("%d", &u);

        delete(root, u);

        p = root->next;

        while(p != NULL)
        {
            printf("%d ", p->val);
            p = p->next;
        }

        printf("\n");

        freelist(root);
    }

    free(root);

    return 0;
}

3.编译源码

$ gcc -o example examle.c -std=c89

4.运行及其结果

$ ./example
6 2 1 2 3 2 5 1 4 5 7 2 2
7 3 1 5 4 

相关文章

网友评论

      本文标题:c语言插入删除链表

      本文链接:https://www.haomeiwen.com/subject/winjrltx.html