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

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
} node;
node *creat(int n)
{
    int i;
    node * head,* p;
    head=(node *)malloc(sizeof(node));
    head->next=NULL;
    for (i=0; i<n; i++)
    {
        p=(node *)malloc(sizeof(node));
        scanf("%d",&p->data);
        p->next=head->next;
        head->next=p;
    }
    return (head);
}
void output(node *head)
{
    node * p;
    p=head->next;
    while(p!=NULL)
    {
        if (p->next==NULL)
            printf("%d\n",p->data);
        else
            printf("%d ",p->data);
        p=p->next;
    }
}
int len(node *head)
{
    int count=0;
    node *p;
    p=head->next;
    while (p!=NULL)
    {
        p=p->next;
        count++;
    }
    return count;
}
void idelete(node *head)
{
    node *p,*q,*tp;
    tp=head->next;
    p=tp->next;
    q=tp;//设置一个q用于跟随p(删除节点必须知道被删节点前的那个节点)
    while (tp!=NULL)//tp表示被比较的数,放于外层循环
    {
        p=tp->next;//给p q赋新的值
        q=tp;
        while(p!=NULL)//p遍历链表,查找是否有重复,到最后一个结束
        {
            if (p->data==tp->data)
            {
                q->next=p->next;
                free(p);
                p=q->next;
            }
            else
            {
                q=q->next;
                p=p->next;
            }
        }
        tp=tp->next;

    }
}
int main()
{
    int n;
    node *head;
    scanf("%d",&n);
    head=creat(n);
    printf("%d\n",len(head));
    output(head);
    idelete(head);
    printf("%d\n",len(head));
    output(head);
    return 0;
}
//利用模块化,把程序分成建表,计算链表长度(其实本题可以并在删除函数里统计)
//,删除重复节点,输出链表这几个功能块,可以比较有调理地解决问题。

猜你喜欢

转载自blog.csdn.net/Here_SDUT/article/details/102970436