您的位置:首页 > 理论基础 > 数据结构算法

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

2016-08-01 20:42 363 查看


这道题的算法思想就是逆序建立一个单链表,然后通过逐个比较元素找到重复元素,关键在于要设定一个指针,让它始终跟在寻找重复元素指针的后面。

代码如下:

#include <stdio.h>

#include <malloc.h>

struct node{

    int data;

    struct node* next;

};

struct node* Createlist(int n){/*逆序建立单链表*/

    struct node* head,*p;

    int i,d;

    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",&d);

        p->data=d;

        p->next=head->next;

        head->next=p;

    }

    return head;

};

int main(){

    struct node* head,*p,*t,*q;

    int n;

    scanf("%d",&n);

    head=Createlist(n);

    q=head->next;

    printf("%d\n",n);

    for(p=head->next;p!=NULL;p=p->next)

        if(p==head->next)

            printf("%d",p->data);

        else

            printf(" %d",p->data);

    printf("\n");

    while(q){

        t=q;/*建立一个指针,始终跟在p指针的后面*/

        p=q->next;

        while(p){

            if(q->data==p->data){/*删除重复元素*/

                t->next=p->next;

                n--;

                p=p->next;

            }

            else{

                t=t->next;

                p=p->next;

            }

        }

        q=q->next;

    }

    printf("%d\n",n);

    for(p=head->next;p!=NULL;p=p->next){

        if(p==head->next)

            printf("%d",p->data);

        else

            printf(" %d",p->data);

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐