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


点击打开链接


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

                                                                                                            Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。
Input
第一行输入表的长度n;
第二行依次输入顺序表初始存放的n个元素值。
Output
第一行输出完成多余元素删除以后顺序表的元素个数;
第二行依次输出完成删除后的顺序表元素。
Example Input
12
5 2 5 3 3 4 2 5 7 5 4 3
Example Output
5
5 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值