已知线性表 LA 和 LB 中的数据元素按值非递减有序排列,现要求将 LA 和 LB 归并为一个新的线性表 LC, 且 LC 中的数据元素仍然按值非递减有序排列。例如,设LA=(3,5,8,11) ,LB=(2,6,8,9,11,15,20) 则LC=(2,3,6,6,8,8,9,11,11,15,20)
输入格式
有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m(0<=m<=100)代表集合A起始有m个元素,后面有m个非递减排序的整数,代表A中的元素。第二行是集合B,第一个整数n(0<=n<=100)代表集合B起始有n个元素,后面有n个非递减排序的整数,代表B中的元素。每行中整数之间用一个空格隔开。
输出格式
每组测试数据只要求输出一行,这一行含有 m+n 个来自集合 A 和集合B 中的元素。结果依旧是非递减的。每个整数间用一个空格隔开。
#include <iostream>
using namespace std;struct ListNode {int val;ListNode* next;ListNode(int x) : val(x), next(NULL) {}
};ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {if (!l1) return l2;if (!l2) return l1;ListNode* dummy = new ListNode(0);ListNode* current = dummy;while (l1 && l2) {if (l1->val <= l2->val) {current->next = l1;l1 = l1->next;} else {current->next = l2;l2 = l2->next;}current = current->next;}current->next = l1 ? l1 : l2;return dummy->next;
}void printList(ListNode* head) {while (head) {cout << head->val << " ";head = head->next;}cout << endl;
}ListNode* createList(int length) {ListNode* head = nullptr;ListNode* prev = nullptr;for (int i = 0; i < length; i++) {int val;cin >> val;ListNode* node = new ListNode(val);if (!head) {head = node;} else {prev->next = node;}prev = node;}return head;
}int main() {int m, n;while (cin >> m) {ListNode* l1 = createList(m);cin >> n;ListNode* l2 = createList(n);ListNode* merged = mergeTwoLists(l1, l2);printList(merged);}return 0;
}