删除单链表的冗余值

23 篇文章 0 订阅

1004:删除单链表的冗余值

Time/Memory Limit:1000 MS/32768 K 
Submitted: 21 Accepted: 18

 Problem Description

给定一个有n个元素的单链表,若单链表中有相等元素则称存在冗余值,要求进行删除操作,即使得单链表中不存在相等元素。

 Input

第一行为一个数字m,表示下面有m组数据,每组数据包括2行:第1行表示单链表的长度n(0<=n<=100,空表的输入只有一行),第2行表示单链表的所有元素。

 Output

每组输出占一行,单链表的每两个元素之间有一空格。输出删除冗余元素后的单链表的所有元素(空表输出一空行)。

 Sample Input

2
8
9 3 3 8 7 8 8 7
10
9 3 3 25 8 3 3 8 3 7

 Sample Output

9 3 8 7
9 3 25 8 7
#include<iostream>
#include<stdio.h>
const int MAX=21;
using namespace std;
class List {
public:
    struct node {
        int data;
        int count;
        node* next;
    };
    node* head;
public:
    List() {
        head=new node;
        head->next=NULL;
    }
    void Creat(int n) {

        node* r=head;
        for(int i=0; i<n; i++) {
            int num;
            cin>>num;
            node* s=new node;
            s->data=num;
            s->count=1;
            r->next=s;
            r=s;
        }
        r->next=NULL;
    }
    void Print() {
        node* p=head->next;
        if(p) {
            while(p->next) {
                cout<<p->data<<" ";
                p=p->next;
            }
            cout<<p->data<<endl;

        } else {
            cout<<endl;
        }
    }
    void DeleteRedudancyValue() {

        if(head->next==NULL||head==NULL) return;
        for(node* p=head->next; p!=NULL; p=p->next) {
            for(node* q=head->next; q&&q!=p; q=q->next) {
                if(p->data==q->data)
                    p->count++;
            }
        }

        node* pre=head;
        node* cur=head->next;
        while(cur) {
            if(cur->count>1) {
                node* s=cur;
                pre->next=cur->next;
                cur=cur->next;
                delete s;
            } else {
                pre=cur;
                cur=cur->next;
            }
        }
    }
};
int main() {
    int T;
    while(cin>>T) {
        while(T--) {
            int n;
            cin>>n;
            List list;
            list.Creat(n);
            list.DeleteRedudancyValue();
            list.Print();
        }
    }
    return 0;
}

方法二删除:

void remove()
{
   node* newnode=head->next;
   while(newnode)
   {
       node* cur=newnode->next;
       node* pre=newnode;
       while(cur)
       {
           if(cur->data==newnode->data)
           {
                node* r=cur;
               pre->next=cur->next;
               cur=cur->next;
               delete r;
           }
           else
           {
               pre=cur;
               cur=cur->next;
           }
       }
       newnode=newnode->next;
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值