• TZOJ 5347: 数据结构实验:删除链表元素


    描述

    完成链表的创建、元素查找和删除等操作。

    部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

    void PrintLinkList(Node *head)
    {
        int flag = 0;
        Node *p = head->next, *q;
        while(p)
        {
            if(flag)
                printf(" ");
            flag = 1;
            printf("%d", p->data);
            q = p;
            p = p->next;
            free(q);
        }
        free(head);
    }
    
    int main()
    {
        int n, x;
        scanf("%d", &n);
        Node *head = CreateLinkList(n);
        scanf("%d", &x);
        Node *p = Find(head, x);
        Delete(p);
        PrintLinkList(head);
        return 0;
    }

    输入

    输入数据第一行为n,表示链表元素个数,第二行为n个整数,表示节点元素值(所有元素值不相等)。

    第三行为删除的元素值,一定存在于链表中。

    输出

    输出删除后的链表元素,每个元素值之间用一个空格隔开。

    样例输入

     5
    1 2 3 4 5
    3

    样例输出

     1 2 4 5

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    typedef struct Node{
        int data;
        struct Node *next;
    }Node;
    Node* CreateLinkList(int n)
    {
        Node *head,*p;
        head=(Node*)malloc(sizeof(Node));
        head->next=NULL;
        p=head;
        while(n--)
        {
            int a;
            scanf("%d",&a);
            p->next=(Node*)malloc(sizeof(Node));
            p=p->next;
            p->data=a;
            p->next=NULL;
        }
        return head;
    }
    Node* Find(Node *head,int n)
    {
        Node *p;
        p=head;
        while(p->next->data!=n)
        {
            p=p->next;
        }
        return p;
    }
    void Delete(Node *p)
    {
        Node *q;
        q=(Node*)malloc(sizeof(Node));
        q->next=(Node*)malloc(sizeof(Node));
        q=p->next;
        p->next=q->next;
        free(q);
    }
    void PrintLinkList(Node *head)
    {
        int flag = 0;
        Node *p = head->next, *q;
        while(p)
        {
            if(flag)
                printf(" ");
            flag = 1;
            printf("%d", p->data);
            q = p;
            p = p->next;
            free(q);
        }
        free(head);
    }
    
    int main()
    {
        int n, x;
        scanf("%d", &n);
        Node *head = CreateLinkList(n);
        scanf("%d", &x);
        Node *p = Find(head, x);
        Delete(p);
        PrintLinkList(head);
        return 0;
    }
  • 相关阅读:
    JVM如何执行方法调用
    JVM如何实现反射
    JVM是如何处理异常的
    Java类加载
    windows-Kafka安装
    Google Eventbus简单使用
    队列c#版
    python 元类

    Spring Mvc 笔记二之异常和文件上传
  • 原文地址:https://www.cnblogs.com/andrew3/p/8689281.html
Copyright © 2020-2023  润新知