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

来源:互联网 发布:联合办学知乎 编辑:程序博客网 时间:2024/06/06 01:43

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

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic

Problem Description

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

Input

第一行输入元素个数 n (1 <= n <= 15);
第二行输入 n 个整数,保证在 int 范围内。

Output

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

Example Input

1021 30 14 55 32 63 11 30 55 30

Example Output

1030 55 30 11 63 32 55 14 30 21730 55 11 63 32 14 21

Hint

Author

不得使用数组! 

思路:想好需要几个指针(p,q)

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
typedef int status;
typedef int element;
struct mode
{
    element data;
    struct mode *next;
};
struct mode *creat1(int n)
{
    struct mode *head,*l;
    int c;
    head=(struct mode *)malloc(sizeof(struct mode));
    head->next=NULL;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&c);
        l=(struct mode *)malloc(sizeof(struct mode));
        l->data=c;
        l->next=head->next;
        head->next=l;
    }
    return head;
};
void show(struct mode *head)
{
    struct mode *p;
    p=head->next;
    while(p!=NULL)
    {
        if(p->next==NULL)
        printf("%d\n",p->data);
        else
            printf("%d ",p->data);
        p=p->next;
    }
}
struct mode *paixu(struct mode *head)
{
    struct mode *q,*p;
    int t;
    p=head->next;
    while(p->next!=NULL)
    {
        q=p->next;
        while(q!=NULL)
        {
            if(p->data>q->data)
            {
                t=p->data;
                p->data=q->data;
                q->data=t;
            }
            q=q->next;
        }
        p=p->next;
    }
    return head;
};
struct mode *shanchu(struct mode *head,int n)
{
    struct mode *p,*q,*r;
    p=head->next;
    while(p!=NULL)
    {
        q=p;
        while(q->next!=NULL)
        {
            r=q->next;
            if(p->data==r->data)
            {
                q->next=r->next;
                free(r);//释放没用的空间
                n--;
            }
            else
            q=q->next;//删除一个元素后q此时代表的元素已经不同,所以删完元素后q不能后移,只有没删元素是才能后移(可用多个相同的元素调试)
        }
        p=p->next;
    }
    printf("%d\n",n);
    return head;
};
int main()
{
    struct mode *head;
    int n;
    cin>>n;
    head=creat1(n);
    printf("%d\n",n);
    show(head);
    head=shanchu(head,n);
    show(head);
    return 0;
}

阅读全文
0 0
原创粉丝点击