数据结构实验之链表七:单链表中重复元素的删除 SDUT OJ C语言 2122

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

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

Input

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

Output

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

Sample Input

10
21 30 14 55 32 63 11 30 55 30

Sample Output

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
    int i;
    struct node *head,*p;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;//申请一个头节点让它为空
    for(i=1; i<=n; i++)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=head->next;//要逆序插入链表就要把顺序输入的p结点插在链表最后,我们假设已经有头结点和p,如果再插入一个新的结点,新的结点就要与p连接起来,如果要连接起来那就让新的结点指向p的地址,p的地址由head->next记着,新的p->next=head->next,保存下head的指针域再给他一个新的指针域同时让头结点和新的p连接在一起,就让head->next=新的p
        head->next=p;//建立p之后
    }
    return head;
};
int retu(struct node *head,int n)
{
    struct node *x,*q,*z;
    x=head->next;//head是一个建好的链表,让x指向第一个数据,建立q,z往下走与x中的数据比较
    while(x)//只要x不为空
    {
        q=x;//q从x所在的数据往下走和后面的所有数据一一比较
        z=q->next;
        while(z)
        {
            if(z->data==x->data)//是与最开头的数据比较
            {
                q->next=z->next;//如果数据相等把结点z删除,先保存下z下面的一个地址,让q指向z后面,链接q和z后面的链表
                z=q->next;//z继续往后走比较数据
                n--;//统计删除后结点数目
            }
            else
            {
                z=z->next;
                q=q->next;
            }
        }
        x=x->next;
    }
    return n;
}
void print(struct node *head)
{
    int n=0;
    struct node *p;
    p=head->next;
    while(p)//只要p不为空
    {
        n++;
        if(n==1)
            printf("%d",p->data);
        else
            printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
        p=p->next;
    }
    printf("\n");//n保证空格数量完全一致
}
int main()
{
    struct node *head;
    int n,m;
    scanf("%d",&n);
    head=creat(n);
    printf("%d\n",n);
    print(head);
    m=retu(head,n);
    printf("%d\n",m);
    print(head);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40354578/article/details/81381040