删除重复元素(结构体+链表)

题目描述

编写三个函数,分别实现如下功能:

1)链表的尾插法创建;

2)删除链表中重复元素;

3)输出链表。

主函数调用上述函数,完成链表的创建及重复元素的删除,并输出链表。

输入

测试次数t

每组测试数据格式为:n 后跟n个整数

输出

对每组测试数据,输出删除重复元素的链表。

样例输入

3
10 -10 2 5 32 5 5 9 11 100 100
5 1 2 3 1 2
5 10 10 10 11 12

样例输出

-10 2 5 32 9 11 100
1 2 3
10 11 12

代码实现:

//
// Created by HP on 2018/3/26.
//
#include <iostream>
using namespace std;
struct node{
    int num;
    node *next;
};
int n;
void CreateList(node *head)
{
    node *tail=head;
    int data;
    int i;
    for(i=0;i<n;i++){
        cin>>data;
        node *s=new node;//创建新的节点
         s->num=data;
        s->next=NULL;
        tail->next=s;//将新结点插入链表中
         tail=s;
    }
}
void ShowList(node *head)
{
    node *display=head->next;
    cout<<display->num;
    display=display->next;
    while(display){
        cout<<" "<<display->num;
        display=display->next;
    }
    cout<<endl;
}
int Deletelist(node *head)
{
    node *ptr,*p;
    ptr=head->next;
    while(ptr){
        p=ptr;
        while(p->next){
            int flag=0;
            if(p->next->num==ptr->num){
                node *temp=p->next;
                p->next=p->next->next;
                delete(temp);
                temp=NULL;
                flag=1;
            }
            if(flag==0)
                p=p->next;
        }
        ptr=ptr->next;
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        cin>>n;
        node *head=new node;
        head->next=NULL;
        CreateList(head);//创建
         Deletelist(head);
        ShowList(head);//输出
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zzzzhdx/article/details/79704556