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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

12
5 2 5 3 3 4 2 5 7 5 4 3

示例输出

5
5 2 3 4 7

提示

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

思路:感觉这个解题方法和链表如出一辙,顺序建表,删除重复元素。

代码:

#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
    struct node *next;
    int data;
};
int main()
{
    int n,a;
    //顺序建立链表
    struct node *head,*tail,*p,*q,*s;
   head=(struct node *)malloc(sizeof (struct node ));
    head->next=NULL;
    tail=head;
    cin>>n;
    int i;
    int k=0;
    for(i=0;i<n;i++)
    {
       p=(struct node *)malloc(sizeof(struct node ));
        cin>>a;
        p->data=a;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }

    p=head->next;
    while(p)
    {
        q=p;
        while(q->next)
        {
            if(q->next->data!=p->data)
            {
                q=q->next;
            }
            else
            {
                k++;
                s=q->next;
                q->next=s->next;
                free(s);
            }
        }
        p=p->next;
    }
    cout<<n-k<<endl;
    p=head->next;
    while(p!=NULL)
    {
      if(p->next==NULL)
      {
          cout<<p->data<<endl;
      }
        else
            cout<<p->data<<' ';
        p=p->next;
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值