数据结构上机测试1:顺序表的应用

来源:互联网 发布:蒙文软件免费下载 编辑:程序博客网 时间:2024/06/06 18:26


点击打开链接


                                                                       数据结构上机测试1:顺序表的应用

                                                                                                            Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatisticDiscuss

Problem Description

在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。

Input

第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。

Output

第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。

Example Input

125 2 5 3 3 4 2 5 7 5 4 3

Example Output

55 2 3 4 7

Hint

用尽可能少的时间和辅助存储空间。

Author

/****************一开始没注意到要输出元素的个数 错了 20多发 后来。。。。。。。。。。恨死自己了*********/

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    struct node *next,*left;
};
struct node * creat(int n)///顺序建立双向链表
{
    struct node *head=new node,*tail,*q;
    head->next=head->left=NULL;///初始化
    tail=head;
    while(n--)
    {
        q=new node ;
        cin>>q->data;
        q->next=NULL;
        q->left=NULL;
        tail->next=q;
        q->left=tail;
        tail=q;
    }
    tail->next=NULL;
    return head;
}
void dell(struct node *head,int *n)///删除链表中的重复元素
{
    struct node *q=head->next,*p;
    if(head->next==NULL)
        return;
    while(q->next)
    {
        p=q->next;///用q来查找相同元素
        while(p)
        {
            if( p->data == q->data )///找到相同元素 删除
            {
                if(p->next==NULL)///p是最后一个节点
                {
                    p->left->next=NULL;
                    free(p);
                    (*n)--;
                    break;
                }
                else
                {
                    struct node *t=p->next;///相tongjiedian得下一个值
                    struct node *t2=p->left;///相同节点的上一个节点
                    t2->next=t;
                    t->left=t2;
                    free(p);
                    p=t;
                    (*n)--;
                }
            }
            else p=p->next;///不是相同元素向后移
        }
        if(q->next)///如果 p不是链表的最后一个继续向后移
            q=q->next;
       else break;
    }
}
void output(struct node *head)///遍历链表
{
    struct node *p=head->next;
    while(p)
    {
        cout<<p->data;
        if( p->next )
        {
            cout<<" ";
        }
        else cout<<'\n';
        p=p->next;
    }
}
int main()
{
    int n;
    cin>>n;
    struct node *head=creat(n);///顺序建立双向链表
    dell(head,&n);///删除链表中的重复元素
    cout<<n<<endl;
    output(head);///遍历双向链表
    return 0;
}




0 0