顺序表的应用(删除链表重复元素)

数据结构上机测试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<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int data;
    struct node *next;
} node;
int main()
{
    int n,a;
    scanf("%d",&n);
    node *p,*q,*head,*tail;
    head=(node*)malloc(sizeof(node));
    head->next=NULL;
    tail=head;
    a=n;
    while(a--)//创建顺序链表
    {
        p=(node*)malloc(sizeof(node));
        scanf("%d",&p->data);
        tail->next=p;
        tail=p;
    }
    p=(node*)malloc(sizeof(node));//此处在链表最后再创建一个空的节点,以便于后续的删除操作
    p->next=NULL;
    tail->next=p;
    tail=head->next;
    while(tail->next!=NULL)//从第一个元素开始检测
    {
        a=tail->data;
        p=tail;
        q=p->next;
        while(q->next!=NULL)//检测每一个元素,是否与当前元素相同,
        {
            if(q->data==a)//相同则删除
            {
                p->next=q->next;
                free(q);
                q=p->next;
                n--;
            }
            else//不同则跳到下一组元素,此处让标记变量先后跳;
            {
                p=q;
                q=q->next;
            }
        }
        tail=tail->next;//此处改变需要检测的变量。
    }
    printf("%d\n",n);
    for(tail=head->next; tail->next->next!=NULL; tail=tail->next)//安要求打印。
        printf("%d ",tail->data);
    printf("%d\n",tail->data);
    return 0;
}
 
习惯把代码放到一起,感觉使用一次的代码用调用函数非常麻烦,还容易在传递参数时出错(个人习惯和水平决定,本人水平确实不高);所以习惯一起写。
posted @ 2013-04-05 00:02  孔凡凯凯  阅读(772)  评论(0编辑  收藏  举报