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
  • 相关阅读:
    Ie console未定义
    jquery bind和live区别
    php insert 空
    ie8及以下不支持getElemlentsByClassName
    jquery ajax parseerror
    你的灯亮着吗——发现问题的真正所在(摘录)
    转:getElementById引起的jQuery的选择器bug
    JS判断是否为数字、JS判断是否为整数、JS判断是否为浮点数
    Microsoft .NET Framework 4 (Standalone Installer)
    Not enough memory is available to complete this request
  • 原文地址:https://www.cnblogs.com/momo-88/p/8909478.html
Copyright © 2011-2022 走看看