题目描述: 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(hint: 请务必使用链表。)
- 输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为两个整数n和m(0<=n<=1000, 0<=m<=1000):n代表将要输入的第一个链表的元素的个数,m代表将要输入的第二个链表的元素的个数。
下面一行包括n个数t(1<=t<=1000000):代表链表一中的元素。接下来一行包含m个元素,s(1<=t<=1000000)。
- 输出:
-
对应每个测试案例,
若有结果,输出相应的链表。否则,输出NULL。
- 样例输入:
-
5 2 1 3 5 7 9 2 4 0 0
- 样例输出:
-
1 2 3 4 5 7 9 NULL
-
#include <iostream> using namespace std; #include <stdio.h> #include <malloc.h> struct Node{ int val; Node *next; }; Node* mergeList(Node *list_a, Node* list_b) { if(NULL == list_a && NULL != list_b) return list_b; if(NULL != list_a && NULL == list_b) return list_a; if(NULL == list_a && NULL == list_b) return NULL; Node *pMergeList = NULL; if(list_a->val < list_b->val) { pMergeList = list_a; pMergeList->next = mergeList(list_a->next, list_b); } else { pMergeList = list_b; pMergeList->next = mergeList(list_a, list_b->next); } return pMergeList; } void insert(Node *list_head_h, int val) { Node * list_head = list_head_h; while(list_head->next!=NULL) { list_head = list_head->next; } Node *tmp = (Node *)malloc(sizeof(Node) * 1); tmp->next = NULL; tmp->val = val; list_head->next = tmp; } void print(Node *list_head1) { Node *list_head = list_head1->next; printf("%d", list_head->val); list_head = list_head->next; while(list_head!=NULL) { printf(" %d", list_head->val); list_head = list_head->next; } printf("\n"); } int main() { int m, n, tmp; Node AHead, BHead; while(scanf("%d %d",&n, &m)!=EOF ) { if(0==n && 0==m) { printf("NULL\n"); continue; } AHead.val = -1; AHead.next = NULL; BHead.val = -1; BHead.next = NULL; while(n--) { scanf("%d", &tmp); insert(&AHead, tmp); } while(m--) { scanf("%d", &tmp); insert(&BHead, tmp); } AHead.next = mergeList(AHead.next, BHead.next); print(&AHead); } } /************************************************************** Problem: 1519 User: hrdjmax2 Language: C++ Result: Accepted Time:670 ms Memory:4688 kb ****************************************************************/
本文介绍如何高效地合并两个单调递增的链表,确保合并后的链表仍然保持单调递增特性,并通过实例演示了实现过程。

被折叠的 条评论
为什么被折叠?



