Link: http://pat.zju.edu.cn/contests/ds/2-11
Two non-descending linked list sequences S1 and S2 are known. The design function constructs a new non-descending linked list S3.
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 new non-descending linked list after merging in a row. Separate the numbers with spaces. No extra spaces are allowed at the end. If the new linked list is empty, the output is "null ".
Sample input and output:
Serial number |
Input |
Output |
1 |
1 3 5 -12 4 6 8 10 -1 |
1 2 3 4 5 6 8 10 |
2 |
1 2 3 4 5 -11 2 3 4 5 -1 |
1 1 2 2 3 3 4 4 5 5 |
3 |
-1-1 |
NULL |
PS: I personally think it is too complicated to use a linked list, so we use vector, 233333333 ......
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++; } else { c.push_back(b[j]); j++; } } if(i < len1) { for(int l = i; l < len1; l++) { c.push_back(a[l]); } } else { for(int l = j; l < len2; l++) { c.push_back(b[l]); } } int len3 = c.size(); if(!len3) { printf("NULL\n"); } 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-11. Merge the sequences of two ordered linked lists (15) (zjupat is implemented using vector)