zoukankan      html  css  js  c++  java
  • 数据结构:删除链表元素

    描述

     

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

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

    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<string.h>
    
    typedef struct node{
        int data;
        struct node* next;
    }Node;
    
    Node* CreateLinkList(int n){
        Node *head,*p;
        head=(Node*)malloc(sizeof(Node));
        head->next=(Node*)malloc(sizeof(Node));
        p=head;
        while(n--){
            int m;
            scanf("%d",&m);
            p->next=(Node*)malloc(sizeof(Node));
            p=p->next;
            p->data=m;
            p->next=NULL;
        }
        return head;
    }
    
    Node* Find(Node *head,int x){
        Node *p;
        p=head;
        while(p->next->data!=x){
            p=p->next;
        }
        return p;
    }
    
    void Delete(Node *h){
        Node *p,*q;
        q=h->next;
        h->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;
    }
    View Code
  • 相关阅读:
    SDOI 2016 数字配对
    SDOI 2016 征途 决策单调性
    SDOI 2016 生成魔咒
    SDOI 2016 排列计数
    【SC主题公园杯】三个袋子 = =不动脑的后果
    【BZOJ3050】【USACO 2013 Jan Gold金组】坐座位 Seating
    MillerRabin 快速的素数概率判定法
    [POJ3189][cqbzoj1640]稳定的奶牛分配 解题报告
    最大流 isap 模板
    【POJ 1324】Holedox Moving A*宽搜
  • 原文地址:https://www.cnblogs.com/momo-88/p/8909478.html
Copyright © 2011-2022 走看看