[剑指offer-1519]合并两个排序的链表
来源:互联网 发布:电脑怎么隐藏软件 编辑:程序博客网 时间:2024/05/29 06:50
题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
(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 <stdio.h>#include <stdlib.h>typedef struct Node{ int value; struct Node* next;}Node,*pNode;pNode createList(int n){ pNode head = NULL; pNode current = NULL; while(n--){ int value; scanf("%d",&value); pNode newNode = (pNode)malloc(sizeof(Node)); newNode->value =value; newNode->next = NULL; if(head == NULL){ head = newNode; current = head; }else{ current->next = newNode; current = current->next; } } return head;}pNode mergeList(pNode list1 , pNode list2){ if(list1 == NULL) return list2; if (list2 == NULL) { return list1; } pNode mergeHead = NULL; if(list1->value < list2->value){ mergeHead = list1; mergeHead->next = mergeList(list1->next, list2); }else{ mergeHead = list2; mergeHead->next = mergeList(list2->next,list1); } return mergeHead;}void printList(pNode head){ if(head == NULL){ printf("NULL\n"); return; } pNode tmp = head; while (tmp) { if(tmp->next == NULL) printf("%d\n",tmp->value); else printf("%d ",tmp->value); tmp = tmp->next; }}int main(int argc, const char * argv[]) { // insert code here... int m , n; while (scanf("%d %d",&n,&m)!=EOF) { pNode list1 = createList(n); pNode list2 = createList(m); pNode merge = mergeList(list1, list2); printList(merge); } return 0;}
0 0
- [剑指offer-1519]合并两个排序的链表
- 剑指Offer题目1519:合并两个排序的链表
- 剑指offer 17-合并两个排序表的链表
- 剑指Offer之合并两个排序的链表
- 剑指offer:合并两个排序的链表
- 剑指offer:合并两个排序的链表
- 【剑指offer】Q17:合并两个排序的链表
- 剑指offer-17:合并两个排序的链表
- 剑指offer系列源码-合并两个排序的链表
- 剑指offer--合并两个排序的链表
- 剑指offer之合并两个排序的链表
- 剑指Offer之 - 合并两个排序的链表
- 剑指offer:合并两个排序的链表
- 剑指Offer-合并两个排序的链表
- 剑指offer:合并两个排序的链表 代码实现
- 《剑指Offer》面试题:合并两个排序的链表
- 合并两个排序的链表(剑指offer)
- 《剑指offer》合并两个排序的链表
- 微信抢红包算法实现-cocos2d-x版
- ubuntu lamp下安装imageMagick
- vb学习之一
- DG保护模式--3种
- java基础总结 --- enum枚举实现多路分发 石头、剪刀、布游戏示例
- [剑指offer-1519]合并两个排序的链表
- JDK中自带xml和对象互转方法
- 转自coolshell--vim的基本操作
- vb学习之二
- vb学习之三
- vb学习之四
- HDOJ 2046 骨牌铺方格
- 终止一个线程的特殊方法
- vb学习之五