SDUTACM数据结构上机测试2-2:单链表操作B

来源:互联网 发布:java的clone方法 编辑:程序博客网 时间:2024/05/18 01:00

题目描述

按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。

输入

第一行输入元素个数n;
第二行输入n个整数。

输出

第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。

示例输入

1021 30 14 55 32 63 11 30 55 30

示例输出

1030 55 30 11 63 32 55 14 30 21730 55 11 63 32 14 21
纯属水题:
#include<stdio.h>#include<string.h>#include<stdlib.h>struct hh{    int data;    struct hh *next;};void main(){    int n,i,k=1,j,s=1,m;    struct hh *head,*p,*t,*t1;    scanf("%d",&n);    m=n;    head=(struct hh *)malloc(sizeof(struct hh));    head->next=NULL;    for(i=0;i<n;i++)    {        p=(struct hh *)malloc(sizeof(struct hh));        scanf("%d",&p->data);        p->next=head->next;        head->next=p;    }    p=head->next;    printf("%d\n",n);    for(i=0;i<n-1;i++)    {         printf("%d ",p->data);         p=p->next;    }    printf("%d\n",p->data);    t1=head->next;    t=t1->next;    for(i=1;i<n;i++)
    {        p=head->next;        for(j=0;j<s;j++)        {            if(t->data==p->data)    {                k=0;                break;    }            p=p->next;}        if(k==1){            if(t->next!=NULL)    {                t1=t1->next;                t=t->next;                s++;    } }        else if(k==0){             t1->next=t->next;             free(t);             m--;             k=1;             t=t1->next;}    }    p=head->next;    printf("%d\n",m);    for(i=0;i<m-1;i++)    {         printf("%d ",p->data);         p=p->next;    }    printf("%d\n",p->data);}


 
1 0