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

来源:互联网 发布:淘宝api 源码下载 编辑:程序博客网 时间:2024/06/05 09:22

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

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

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

55 2 3 4 7

提示

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

解法(1)链表

#include<iostream>  #include<stdlib.h>  #include<stdio.h>  using namespace std;  int k=0;  struct node  {  int num;  struct node *next;  };  struct node *creat(struct node *head,int n)  {  int i,j;  struct node *p,*q,*tail;  q=head;  for(i=0;i<n;i++)  {  scanf("%d",&j);  if(i==0)  {  p=(struct node *)malloc(sizeof(struct node));  p->num=j;  p->next=q->next;  q->next=p;  q=p;  k++;  }  else  {  tail=head;  tail=tail->next;  while(tail!=NULL)  {  if(tail->num==j)  break;  tail=tail->next;  }  if(tail==NULL)  {  p=(struct node *)malloc(sizeof(struct node));  p->num=j;  p->next=q->next;  q->next=p;  q=p;  k++;  }  }  }  return head;  }  int main()  {  int i,j,n,m,t;  struct node *head2,*tail,*p,*q,*v;  head2=(struct node *)malloc(sizeof(struct node));  head2->next=NULL;  scanf("%d",&n);  head2=creat(head2,n);  printf("%d\n",k);  q=head2;  q=q->next;  for(j=0;j<k;j++)  {  if(j==0)  printf("%d",q->num);  else  printf(" %d",q->num);  q=q->next;  }  printf("\n");  }

解法(2)数组

#include<stdio.h>  int main()  {      int i,j,n,m,a[1000],b=0,d;      scanf("%d",&n);      for(i=0;i<n;i++)      {          d=0;          if(i==0)              scanf("%d",&a[0]);          else          {              scanf("%d",&m);          for(j=0;j<=b;j++)              if(m==a[j])                  d=1;              if(d==0)              {                  b++;                  a[b]=m;              }      }      }      printf("%d\n",b+1);      for(i=0;i<=b;i++)      {          if(i==0)  printf("%d",a[i]);          else              printf(" %d",a[i]);      }          printf("\n");  } 


0 0
原创粉丝点击