• 8817


    Problem Description 
     

    按照数据输入的顺序建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最初输入的一个)。

    Input

    第一行输入元素个数n;第二行输入n个整数;处理到文件结束.

    Output

    第1行输出删除重复元素后的单链表元素个数;
    第2行输出删除重复元素后的单链表;

    Sample Input

    10
    21 30 14 55 32 63 11 30 55 30
    

    Sample Output

    7
    21 30 14 55 32 63 11
    

    Source

    不得使用数组!

    #include<iostream>
    #include<stdio.h>
    const int MAX=21;
    using namespace std;
    class List 
    {
    public:
        struct node 
        {
            int data;
            int count;
            node* next;
        };
        node* head;
    public:
        List()
         {
            head=new node;
            head->next=NULL;
        }
        void Creat(int n) 
        {
     
            node* r=head;
            for(int i=0; i<n; i++) 
            {
                int num;
                cin>>num;
                node* s=new node;
                s->data=num;
                s->count=1;
                r->next=s;
                r=s;
            }
            r->next=NULL;
        }
        void Print() 
        {
            
            node* p1=head->next;
            node* p=head->next;
            int count = 0;
            while(p1 != NULL)
             {
              p1 = p1->next;
                count++;
              }
             cout<<count<<endl;
            if(p) 
               {
                while(p->next) {
                    cout<<p->data<<" ";
                    p=p->next;
                }
                cout<<p->data<<endl;
     
            }
             else 
            {
                cout<<endl;
            }
        }
        void DeleteRedudancyValue()
         {
     
            if(head->next==NULL||head==NULL) return;
            for(node* p=head->next; p!=NULL; p=p->next)
             {
                for(node* q=head->next; q&&q!=p; q=q->next)
                {
                    if(p->data==q->data)
                        p->count++;
                }
            }
     
            node* pre=head;
            node* cur=head->next;
            while(cur) 
            {
                if(cur->count>1) 
                {
                    node* s=cur;
                    pre->next=cur->next;
                    cur=cur->next;
                    delete s;
                } else {
                    pre=cur;
                    cur=cur->next;
                }
            }
        }
    };
    int main() 
    {
        int n;
        while(cin>>n)
         {
                    
                List list;
                list.Creat(n);
                list.DeleteRedudancyValue();
                list.Print();
            
        }
        return 0;
    }
  • 相关阅读:
    向值栈放List集合
    向值栈放对象
    向值栈放数据
    wsgi初探
    python_swift_project_swift使用
    python_swift_project_middleware
    ubuntu 安装 swift
    20140905
    eventlet
    resource
  • 原文地址:https://www.cnblogs.com/ilovetheworld/p/10140499.html
Copyright © 2020-2023  润新知