1. 题目
示例输入
8 5 6
1 2 3 4 5 6 6 7
2 3 5 9 12
2 4 5 6 12 13
示例输出
1 3 4 6 6 7
2. 代码
- 数组方式
/*8 5 6
1 2 3 4 5 6 6 7
2 3 5 9 12
2 4 5 6 12 13*/
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int m, n, p;
int quit=0;
int q=0, i=0, j=0;
int a[100], b[100], c[100];
cin >> m >> n >> p;
for(int k=0; k<m; k++){
cin >> a[k];
}
for(int k=0; k<n; k++){
cin >> b[k];
}
for(int k=0; k<p; k++){
cin >> c[k];
}
while(i<n && j<p){
if(b[i]==c[j]){
while(a[q]<=b[i]){
if(a[q]==b[i]){
a[q] = 0;
}
q++;
if(q>=m){
quit = 1;
break;
}
}
if(quit==1){
break;
}
i++;
j++;
}
else if(b[i]<c[j]){
i++;
}
else{
j++;
}
}
for(int z=0; z<m; z++){
if(a[z]!=0){
cout << a[z] << " ";
}
}
return 0;
}
- 链表方式
yysy,链表方式真是容易出bug。
- 有时候忘记p=p->next,还不容易看出来,一本正经看半天。
- 判断到链表尾部的时候(比如本题的a),如果忘记判断是否为空就又死循环了。
//8 5 6
//1 2 3 4 5 6 6 7
//2 3 5 9 12
//2 4 5 6 12 13
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Node;
void createList(Node *head, int n){
Node *p = head;
for(int i=0; i<n; i++){
p->next = (Node*) malloc(sizeof(Node));
cin >> p->next->data;
// cout << p->next->data << endl;
p = p->next;
}
p->next = NULL;
}
void deletea(Node* heada, Node* headb, Node* headc){
Node *a = heada, *b = headb->next, *c = headc->next;
Node *p = a->next;
while(b && c && a->next){
if(b->data == c->data){
int tmp = b->data;
while(p->data < tmp && p->next){
// cout << p->data << " ";
p = p->next;
a = a->next;
}
while(p->data == tmp && p->next){ // 删除节点
p = p->next;
a->next = p;
}
b = b->next;
c = c->next;
}
else if(b->data > c->data){
c = c->next;
}
else{
b = b->next;
}
}
}
void outputList(Node *head){
Node *p = head->next;
while(p){
cout << p->data << " " ;
p = p->next;
}
}
int main(int argc, char** argv) {
int m, n, p;
cin >> m >> n >> p;
Node *heada, *headb, *headc;
heada = (Node*) malloc(sizeof(Node));
headb = (Node*) malloc(sizeof(Node));
headc = (Node*) malloc(sizeof(Node));
createList(heada, m);
createList(headb, n);
createList(headc, p);
deletea(heada, headb, headc);
outputList(heada);
return 0;
}