版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/83214234
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;
}
}