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

本文介绍了一个使用 C 语言实现的链表逆序及删除重复元素的程序。该程序首先创建一个链表,然后对其进行逆序操作,并删除所有重复的元素,最后输出处理后的链表内容。

<code>这里写图片描述</code>

#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>

struct node
{
    int data;
    struct node *next;
};
struct node *h,*p,*t;
int main()
{
    int n;
    h=(struct node *)malloc(sizeof(struct node));
    h->next=NULL;
    t=h;
    scanf("%d",&n);
    int began=n;
    while(n--)
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=NULL;
        t->next=p;
        t=p;
    }
    struct node *q;
    p=h->next;
    q=p->next;
    h->next=NULL;
    while(p)
    {
        p->next=h->next;
        h->next=p;
        p=q;
        if(q)
            q=q->next;
    }
    p=h->next;
    printf("%d\n",began);
    while(p->next)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("%d\n",p->data);
    p=h->next;
    while(p)
    {
        q=p->next;
    t=p;
        while(q)
        {
            if(q->data==p->data)
            {
                t->next=q->next;//t要一直跟在q的后面确保与p相同的元素出现之后能够将其删除
                q=t->next;//q用来循环寻找p后与p值相同的元素
            began--;
            }//找到了就将其删除
            else
            {
                q=q->next;
                t=t->next;
            }//找不到就将q的值后移一位,t紧跟在q的后面
        }
        p=p->next;//后移p
    }
    printf("%d\n",began);
    p=h->next;
    while(p->next)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("%d",p->data);
    return 0;
}

另外一种用函数的代码

这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值