Topic 1519: Merging two sorted lists time limit: 1 seconds memory limit: 128 trillion special subject: No submission: 1309 resolution: 615 Title Description: Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the list to meet the monotone rule. (Hint: Be sure to use a linked list.) Input: The input may contain multiple test samples, and the input ends with EOF. For each test case, enter the first behavior of two integers n and m (0<=n<=1000, 0<=m<=1000): N represents the number of elements of the first linked list that will be entered, and M represents the number of elements of the second linked list to be entered. The following line includes n number t (1<=t<=1000000): Represents the element in the chain table one. The next line contains m elements, s (1<=t<=1000000). Output: corresponding to each test case, if there is a result, output the corresponding linked list. Otherwise, the output is null. Sample input: 5 21 3 5 7 92 40 0 Sample output: 1 2 3 4 5 7 9NULL
#include <stdio.h> #include <iostream>using namespace std;struct listnode{int value; Listnode* next;}; listnode* megerlist (listnode* ahead,listnode* bhead) {if (ahead==null) {return bhead; } if (Bhead==null) {return aHead; } listnode* megeredhead = NULL; if (ahead->value<bhead->value) {megeredhead = AHead; Megeredhead->next = Megerlist (Ahead->next,bhead); }else{megeredhead = Bhead; Megeredhead->next = Megerlist (Ahead,bhead->next); } return megeredhead;} int main () {int n,m; listnode* Anode; listnode* AHead; listnode* BNode; listnode* Bhead; while (scanf ("%d%d", &n,&m)!=eof) {if (n<=0&&m<=0) {printf ("null\n"); Continue }//construct linked list for (int i=0;i<n;i++) {listnode* pnew = new ListNode (); scanf ("%d", &pnew->value); pnew->next=null; if (i==0) {anode = AHead = Pnew; }else{anode->next = pnew; Anode = pnew; }} for (int i=0;i<m;i++) {listnode* pnew = new ListNode (); scanf ("%d", &pnew->value); pnew->next=null; if (i==0) {BNode = Bhead = pnew; }else{bnode->next = pnew; BNode = pnew; }} listnode* Megeredhead = Megerlist (Ahead,bhead); while (Megeredhead->next) {printf ("%d", megeredhead->value); Megeredhead = megeredhead->next; } printf ("%d\n", Megeredhead->value); } return 0;}
OJ Address
Sword refers to offer series source code-merge two sorted list