lintcode:Merge Two Sorted Lists
2016-03-07 15:18
417 查看
Merge two sorted (ascending) linked lists and return it as a new
sorted list. The new sorted list should be made by splicing together
the nodes of the two lists and sorted in ascending order.
Given 1->3->8->11->15->null, 2->null ,
return 1->2->3->8->11->15->null.
题目很简单。
注意一点,最后如果p1或者p2非空时,只需要把p1或p2链接到newp->next即可,而不需要逐个的元素添加。
sorted list. The new sorted list should be made by splicing together
the nodes of the two lists and sorted in ascending order.
Given 1->3->8->11->15->null, 2->null ,
return 1->2->3->8->11->15->null.
题目很简单。
注意一点,最后如果p1或者p2非空时,只需要把p1或p2链接到newp->next即可,而不需要逐个的元素添加。
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param ListNode l1 is the head of the linked list * @param ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { // write your code here ListNode *newl=new ListNode(0); ListNode *newp=newl; ListNode *p1=l1,*p2=l2; while(p1 && p2){ if(p1->val<p2->val){ newp->next=p1; newp=newp->next; p1=p1->next; }else{ newp->next=p2; newp=newp->next; p2=p2->next; } } if(p1){ newp->next=p1; }else{ newp->next=p2; } return newl->next; } };
相关文章推荐
- poj 2478 Farey Sequence(欧拉函数)
- 继承LinearLayout实现大众点评标题和图表的效果
- PAT (Basic Level)1028. 人口普查
- Unity3D 移动平台Path对应路径以及文件路径权限
- MathType插入带序号公式的两种方法
- 在apache hadoop2.6 上部署hive 并将hive数据源存储于Mysql
- 基础排序算法,java实现(快速,冒泡,选择,堆排序,插入)
- M1卡修改各区块控制位值和数据
- js 函数的传值问题
- poj2533
- 【Jmeter】Jmeter聚合报告分析
- git常用命令
- ECS Linux服务器安装JDK配置JAVA环境
- 消息队列MQ】各类MQ比较
- C++文件操作详解(ifstream、ofstream、fstream)
- Python基础学习教程-第2讲安装Python
- NFS mount
- wamp环境项目连接虚拟机mongo出现连接失败,原因是防火墙端口没开
- 【c/c++】单链表、头指针、头结点、首元节点
- 华中科技1199