Problem Description
已知递增有序的单链表A,B,现在要从链表A中删除链表B中存在的元素。若处理后的链表A不为空,则输出链表A中的元素;否则,输出“empty”。
Input
输入的第一行为一个数字T,表示接下来有T组数据;
接下来有T组数据,每组数据占四行:
第一行为一个整数n(0<=n<=25),表是单链表A的表长;
第二行有n个数,表示单链表A中的元素;
第三行为一个整数m(0<=m<=25),表是单链表B的表长;
第四行有m个数,表示单链表B中的元素。
Output
对于每组数据,若处理后的链表A不为空,则输出处理后链表A中的元素,每个元素之间用一个空格分隔;否则,输出“empty”,每组输出占一行。
Sample Input
1 5 1 2 3 4 5 3 2 3 7
Sample Output
1 4 5
代码:
#include<iostream>
#include<stdio.h>
const int MAX=21;
using namespace std;
class List{
public:
struct node{
int data;
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;
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<<"empty"<<endl;
}
}
void Delete(node* headB){
node* Bp=headB->next;
while(Bp){
node* cur=head->next;
node* pre=head;
while(cur){
if(cur->data==Bp->data){
pre->next=cur->next;
cur=cur->next;
}
else{
pre=cur;
cur=cur->next;
}
}
Bp=Bp->next;
}
}
};
int main(){
int T;
while(cin>>T){
while(T--){
int n;
cin>>n;
List A;
A.Creat(n);
int m;
cin>>m;
List B;
B.Creat(m);
A.Delete(B.head);
A.Print();
}
}
return 0;
}