数据结构实验之链表七:单链表中重复元素的删除

来源:互联网 发布:java中编写菱形原理 编辑:程序博客网 时间:2024/05/16 18:34

题目描述

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

输入

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

输出

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

示例输入

10
21 30 14 55 32 63 11 30 55 30

示例输出

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21

提示

来源

不得使用数组!

这几天一直在做单向链表,慢慢的熟悉了,现在打起来也很随意了。

这题,我觉得可能出毛病的地方就是删掉一个之后怎么处理(我开始的时候处理是错的,测例能过,但是交上去运行出错,检查后发现有漏洞,改了之后就AC了)

#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <string>#include <stack>#include <set>#include <queue>#include <algorithm>#define CLR(a, b) memset(a, (b), sizeof(a))#define INF 0x3f3f3f3f#define eps 1e-8using namespace std;typedef struct Node{    int date;    struct Node *next;}node;node *creat(int n){    node *head=(node *)malloc(sizeof(node));    node *r=NULL;    for(int i=0;i<n;i++)    {        int date;        scanf("%d",&date);        if(i==0)        {            head->date=date;            head->next=NULL;            r=head;        }        else{            node *p=(node *)malloc(sizeof(node));            p->date=date;            p->next=r;            r=p;        }    }    return r;}void show(node *head){    node *pr=head;    while(pr->next)    {        printf("%d ",pr->date);        pr=pr->next;    }    printf("%d\n",pr->date);}void delet(int *n,node *head){    node *pr=head;    while(pr->next)    {        node *r=pr;        node *p=r->next;        while(r->next)        {            if(pr->date==p->date)            {                r->next=p->next;                free(p);                (*n)--;                p=r->next;            }            else{            r=r->next;            p=r->next;            }        }        pr=pr->next;    }}int main(){   #ifdef LOCAL    freopen("E://in.txt","r",stdin);   #endif // LOCAL    int n;    while(scanf("%d",&n)!=EOF)    {        node *head=creat(n);        printf("%d\n",n);        show(head);        delet(&n,head);        printf("%d\n",n);        show(head);    }    return 0;}
0 0
原创粉丝点击