【1130】数据结构上机测试1:顺序表的应用 (两种方法) SDUT

来源:互联网 发布:吉他谱软件哪个好 编辑:程序博客网 时间:2024/06/03 12:37

数据结构上机测试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
方法一;将a【k】后的元素依次与a【k】前的元素比较,若a【k】前的元素中没有与当前元素相同的值,则让此元素计入到a【k】前的元素中。
#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){    int n,i,j,k,flag;    int a[1010];    scanf("%d",&n);    for(i=0;i<n;i++)        scanf("%d",&a[i]);    k=1;    for(i=1;i<n;i++)    {        flag=0;        for(j=0;j<k;j++)        {            if(a[i]==a[j])//查找k前是否有与a[i]相同的值            {                flag=1;                break;            }        }        if(flag==0&&j==k)        {            a[k++]=a[i];        }    }    printf("%d\n",k);    for(i=0;i<k;i++)    {        if(i==k-1)            printf("%d\n",a[i]);        else            printf("%d ",a[i]);    }    return 0;}

#include <stdio.h>#include <stdlib.h>struct node{    int data;    struct node *next;};int n;struct node *creat()//建表{    struct node *head,*tail,*p;    int i;    head=(struct node *)malloc(sizeof(struct node));    head->next=NULL;    tail=head;    for(i=0;i<n;i++)    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);        p->next=NULL;        tail->next=p;        tail=p;    }    return head;};int main(){    struct node *head,*p,*tail,*q;    scanf("%d",&n);    head=creat();    tail=head->next;    q=tail;    p=tail->next;    while(tail->next!=NULL)//重复元素删除过程    {        while(p!=NULL)        {            if(p->data==tail->data)            {                q->next=p->next;                free(p);                p=q->next;                n--;            }            else            {                q=p;                p=p->next;            }        }        tail=tail->next;        q=tail;        p=tail->next;    }    printf("%d\n",n);    p=head->next;//输出    while(p!=NULL)    {        if(p->next==NULL)            printf("%d\n",p->data);        else            printf("%d ",p->data);        p=p->next;    }    return 0;}


0 0
原创粉丝点击