實驗項目 2-12:兩個有序鏈表序列的交集

2-12. 兩個有序鏈表序列的交集(20)

時間限制
400 ms
內存限制
64000 kB
代碼長度限制
8000 B
判題程序
Standard

已知兩個非降序鏈表序列S1與S2,設計函數構造出S1與S2的交集新鏈表S3。

輸入格式說明:

輸入分2行,分別在每行給出由若干個正整數構成的非降序序列,用-1表示序列的結尾(-1不屬於這個序列)。數字用空格間隔。

輸出格式說明:

在一行中輸出兩個輸入序列的交集序列,數字間用空格分開,結尾不能有多餘空格;若新鏈表爲空,輸出“NULL”。

樣例輸入與輸出:

序號 輸入 輸出
1
1 2 5 -1
2 4 5 8 10 -1
2 5
2
1 3 5 -1
2 4 6 8 10 -1
NULL
3
1 2 3 4 5 -1
1 2 3 4 5 -1
1 2 3 4 5
4
3 5 7 -1
2 3 4 5 6 7 8 -1
3 5 7
5
-1
10 100 1000 -1
NULL

鏈表標準代碼:

#include <stdio.h>
#include <stdlib.h>
#define LEN (struct node*)malloc(sizeof(struct node))

struct node
{
	int num;
	struct node *next;
};
node *creat()
{
	node *t,*p,*head;
	int n,i=0;
	p=LEN;
	t=p;
	scanf("%d",&p->num);
	head=NULL;
	p->next=NULL;
	while(p->num!=-1){
		if(!i){
			head=p;
			i=1;
		}
		else
			t->next=p;
		t=p;
		p=LEN;
		scanf("%d",&p->num);
		p->next=NULL;
	}
	return head;
}
node *jiao(node *head1,node *head2)
{
	node *head,*t,*p1,*p2,*p;
	int flag=0;
	head=NULL;
	t=head;
	p1=head1;
	p2=head2;
	while(p1&&p2){
		if(p1->num > p2->num)
			p2=p2->next;
		else if(p1->num < p2->num)
			p1=p1->next;
		else{
			p=LEN;
			p->num=p1->num;
			p->next=NULL;
			if(!flag){
				head=p;
				flag=1;
			}
			else
				t->next=p;
			t=p;
			p1=p1->next;
			p2=p2->next;
		}
	}
	return head;
}

void print(node *head)
{
	struct node *p;
	p=head;
	int i=0;
	while(p!=NULL){
		if(i)
			printf(" ");
		i=1;
		printf("%d",p->num);
		p=p->next;
	}
	if(!i)
		printf("NULL");
	printf("\n");
}

int main()
{
	node *head1,*head2;
	head1=creat();
	head2=creat();
	head1=jiao(head1,head2);
	print(head1);
	return 0;
}

vector解法:

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
vector<int> h1,h2,h3;
void creat()
{
	int i,j,n;
	for(i=0;i<2;i++)
	{
		while(1)
		{
			scanf("%d",&n);
			if(n==-1)
			{
				break;
			}
			if(i)
			{
				h2.push_back(n);
			}
			else
			{
				h1.push_back(n);
			}
		}
	}
}
void jiao()
{
	int i,j,a,b;
	a=h1.size();
	b=h2.size();
	i=j=0;
	while(i!=a&&j!=b)
	{
		if(h1[i]<h2[j])
		{
			i++;
		}
		else if(h1[i]>h2[j])
		{
			j++;
		}
		else{
			h3.push_back(h1[i]);
			i++;
			j++;
		}
	}
}
void print()
{
	int i,a;
	a=h3.size();
	if(!a)
	{
		printf("NULL\n");
	}
	else{
		for(i=0;i<a;i++)
		{
			if(i)
			{
				printf(" ");
			}
			printf("%d",h3[i]);
		}
		printf("\n");
	}
}
int main()
{
	creat();
	jiao();
	print();
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章