标签:style java color 使用 strong os
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(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
----------------------------------------------------
/***************************** 有序链表合并 by Rowandjj 2014/7/16 *******************************/ #include<iostream> #include<stdlib.h> #include<stdio.h> using namespace std; typedef struct Node { int data; struct Node *next; }Node,*List; Node* MergeList(List la,List lb) { List lc; if(!la) { return lb; }else if(!lb) { return la; } Node *pa = la,*pb = lb,*pc; if(pa->data < pb->data) { pc = pa; pa = pa->next; }else { pc = pb; pb = pb->next; } lc = pc; while(pa && pb) { if(pa->data < pb->data) { pc->next = pa; pc = pa; pa = pa->next; }else { pc->next = pb; pc = pb; pb = pb->next; } } pc->next = pa ? pa : pb; return lc; } int main() { int n,m,i; int data; while(scanf("%d %d",&n,&m) != EOF) { Node *pCur; List nL = NULL; if(n>0) { nL = (Node*)malloc(sizeof(Node)); if(!nL) { exit(0); } cin>>data; nL->data = data; nL->next = NULL; pCur = nL; for(i = 0; i < n-1; i++) { Node *newNode = (Node*)malloc(sizeof(Node)); if(!newNode) { exit(-1); } cin>>data; newNode->data = data; newNode->next = NULL; pCur->next = newNode; pCur = newNode; } } List mL = NULL; if(m>0) { mL = (List)malloc(sizeof(Node)); if(!mL) { exit(0); } cin>>data; mL->data = data; mL->next = NULL; pCur = mL; for(i = 0; i < m-1; i++) { Node *nodeNew = (Node*)malloc(sizeof(Node)); if(!nodeNew) { exit(-1); } cin>>data; nodeNew->data = data; nodeNew->next = NULL; pCur->next = nodeNew; pCur = nodeNew; } } List newList = MergeList(nL,mL); if(newList != NULL) { Node *p = newList; while(p) { if(p->next == NULL) { cout<<p->data<<endl; }else { cout<<p->data<<" "; } p = p->next; } }else { cout<<"NULL"<<endl; } } return 0; }
//递归版本 Node* MergeList_2(List la,List lb) { if(!la) { return lb; }else if(!lb) { return la; } Node *phead = NULL; if(la->data < lb->data) { phead = la; phead->next = MergeList_2(la->next,lb); }else { phead = lb; phead->next = MergeList_2(la,lb->next); } return phead; }
标签:style java color 使用 strong os
原文地址:http://blog.csdn.net/chdjj/article/details/37885375