a链表删除b链表中相同的值

 

 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

haibianyoushark

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

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

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

打赏作者

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

抵扣说明:

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

余额充值