本文主要是介绍PAT(甲级)2019年秋季考试7-2 Merging Linked Lists (25 分),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
7-2 Merging Linked Lists (25 分)
Given two singly linked lists L1 =a1 →a2 →⋯→an−1 →an and L2 =b1 →b2 →⋯→bm−1 →bm . If n≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a list like a1 →a2 →bm →a3 →a4 →bm−1 ⋯. For example, given one list being 6→7 and the other one 1→2→3→4→5, you must output 1→2→7→3→4→6→5.
Input Specification:
Each input file contains one test case. For each case, the first line contains the two addresses of the first nodes of L1 and L2 , plus a positive N (≤105 ) which is the total number of nodes given. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Data Next
where Address is the position of the node, Data is a positive integer no more than 105 , and Next is the position of the next node. It is guaranteed that no list is empty, and the longer list is at least twice as long as the shorter one.
Output Specification:
For each case, output in order the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 01000 7
02233 2 34891
00100 6 00001
34891 3 10086
01000 1 02233
00033 5 -1
10086 4 00033
00001 7 -1
Sample Output:
01000 1 02233
02233 2 00001
00001 7 34891
34891 3 10086
10086 4 00100
00100 6 00033
00033 5 -1
因为N >=2*M,所以结尾有两种情况我是分开来写了。还有就是把长度小的插入到长度大的,这个要判断过。
#include<bits/stdc++.h>
using namespace std;
struct Node {int address, data, next;
} node[100005];
int main() {int s1, s2, N;scanf("%d %d %d", &s2, &s1, &N);for (int i = 0; i < N; i++) {int id;scanf("%d", &id);scanf("%d %d", &node[id].data, &node[id].next);node[id].address = id;}vector<Node> temp1, temp2, v1, v2;while (s1 != -1) {temp1.push_back(node[s1]);s1 = node[s1].next;}while (s2 != -1) {temp2.push_back(node[s2]);s2 = node[s2].next;}if (temp1.size() > temp2.size()) {v1 = temp1;v2 = temp2;} else {v1 = temp2;v2 = temp1;}reverse(v2.begin(), v2.end());int cnt = 0;if (v1.size() > v2.size() * 2) {for (int i = 0; i < v1.size(); i++) {if (i != v1.size() - 1) {if (i % 2 == 0 || cnt == v2.size()) {printf("%05d %d %05d\n", v1[i].address, v1[i].data, v1[i + 1].address);} else {printf("%05d %d %05d\n", v1[i].address, v1[i].data, v2[cnt].address);printf("%05d %d %05d\n", v2[cnt].address, v2[cnt].data, v1[i + 1].address);cnt++;}} else {printf("%05d %d -1\n", v1[i].address, v1[i].data);}}} else if (v1.size() == v2.size() * 2) {for (int i = 0; i < v1.size(); i++) {if (i % 2 == 0) {printf("%05d %d %05d\n", v1[i].address, v1[i].data, v1[i + 1].address);} else {printf("%05d %d %05d\n", v1[i].address, v1[i].data, v2[cnt].address);if (cnt != v2.size() - 1) printf("%05d %d %05d\n", v2[cnt].address, v2[cnt].data, v1[i + 1].address);else printf("%05d %d -1\n", v2[cnt].address, v2[cnt].data);cnt++;}}}return 0;
}
这篇关于PAT(甲级)2019年秋季考试7-2 Merging Linked Lists (25 分)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!