Link: http://pat.zju.edu.cn/contests/ds/2-12
We know the sequence S1 and S2 of two non-descending linked lists. The design function constructs a new linked list S3 with the intersection of S1 and S2.
Input format description:
The input is divided into two rows. Each row contains a non-descending sequence composed of several positive integers.-1 indicates the end of the sequence (-1 does not belong to this sequence ). Numbers are separated by spaces.
Output format description:
Output the intersection sequence of two input sequences in one row. Separate the numbers with spaces. There cannot be any extra spaces at the end. If the new linked list is empty, the output is "null ".
Sample input and output:
Serial number |
Input |
Output |
1 |
1 2 5 -12 4 5 8 10 -1 |
2 5 |
2 |
1 3 5 -12 4 6 8 10 -1 |
NULL |
3 |
1 2 3 4 5 -11 2 3 4 5 -1 |
1 2 3 4 5 |
4 |
3 5 7 -12 3 4 5 6 7 8 -1 |
3 5 7 |
5 |
-110 100 1000 -1 |
NULL |
PS:
Just like the idea of the previous question, you just need to make a slight change! Similarly, vector 233333 ......
The Code is as follows:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#include <vector>vector<int>a, b, c;int main(){ int tt; while(1) { scanf("%d",&tt); if(tt == -1) break; a.push_back(tt); } while(1) { scanf("%d",&tt); if(tt == -1) break; b.push_back(tt); } int len1 = a.size(); int len2 = b.size(); int i = 0, j = 0; while(i < len1 && j < len2) { if(a[i] == b[j]) { c.push_back(a[i]); i++,j++; } else if(a[i] < b[j]) { // c.push_back(a[i]); i++; } else { // c.push_back(b[j]); j++; } } int len3 = c.size(); if(!len3) { printf("NULL\n"); // return 0; } else { int flag = 0; for(int i = 0; i < len3; i++) { if(flag) { printf(" %d",c[i]); } else { printf("%d",c[i]); flag = 1; } } printf("\n"); } return 0;}
2-12. intersection of two ordered linked list sequences (20) (zjupat is implemented using vector)