• 数据结构之 线性表---单链表操作A (删除链表中的指定元素)


    数据结构上机测试2-1:单链表操作A

    Time Limit: 1000MS Memory limit: 4096K

    题目描述

    输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。

    输入

    第一行输入数据个数n;
    第二行依次输入n个整数;
    第三行输入欲删除数据m。

    输出

    第一行输出原始单链表的长度;
    第二行依次输出原始单链表的数据;
    第三行输出完成删除后的单链表长度;
    第四行依次输出完成删除后的单链表数据。

    示例输入

    10
    56 25 12 33 66 54 7 12 33 12
    12

    示例输出

    10
    56 25 12 33 66 54 7 12 33 12
    7
    56 25 33 66 54 7 33

    代码(比较挫~~~):
    #include <iostream>
    #include <string>
    #include <cstdio>
    #include <string.h>
    #include <algorithm>
    #include <ctype.h>
    
    using namespace std;
    
    struct node
    {
        int data;
        struct node *next;
    };
    
    struct node *creat(int n)
    {
        int i;
        struct node *head, *tail, *p;
        head=new node;
        head->next=NULL;
        tail=head;
    
        for(i=0; i<n; i++)
        {
            p=new node;
            cin>>p->data;
            p->next=NULL;
            tail->next=p;
            tail=p;
        }
        return head;
    }
    
    int main()
    {
        int n, k;
        int len;
        int i, j;
    
        cin>>n;
        struct node *head, *w, *q;
        head = creat(n);
        cin>>k; //输入要被删除的数据
    //输出链表1
        w=head->next;
        len=n;
        cout<<len<<endl;
        for(j=0; j<len; j++)
        {
            if(j==0)
              cout<<w->data;
            else
              cout<<" "<<w->data;
            w=w->next;
        }
        cout<<endl;
    //进行删除操作
        len=n;
        w=head->next;
        q=head; //q的后继是w
        for(j=0; j<n; j++)
        {
            if(w->data == k)
            {
                q->next=w->next; //让前驱指针指向要被删除节点的后继
                w->next=NULL; //将该节点孤立
                delete(w);    //然后删除掉
                len--;     //长度减1
                w=q->next; //w指向q的后继
                if(!w)  //如果w指向为空,直接跳出,没有你要再循环了
                {
                    break;
                }
            }
            else
            {
                w=w->next;  //正常情况下,w和q指针往后移动,寻找要被删除的数值!
                q=q->next;
            }
        }
        cout<<len<<endl;
        w=head->next;
        for(j=0; j<len; j++)
        {
            if(j==0)
              cout<<w->data;
            else
              cout<<" "<<w->data;
            w=w->next;
        }
        cout<<endl;
    
        return 0;
    }
    
  • 相关阅读:
    二叉排序树
    索引顺序表查找(分块查找)
    wpf中的窗口
    递归算法以及汉诺塔
    Net中资源存储的设置
    AutoResetEvent 和ManualResetEvent
    WPF:跨应用程序会话保持和还原应用程序范围的属性
    Base64编码及其作用
    WPF中的应用程序级别Application
    Ajax经典学习教材,IBM官方Ajax教材
  • 原文地址:https://www.cnblogs.com/yspworld/p/4094025.html
Copyright © 2020-2023  润新知