leetcode 021 Merge Two Sorted Lists
2016-04-06 00:33
429 查看
题目
21. Merge Two Sorted ListsMerge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:
简单题,利用链表的特点进行合并。代码:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; else if(l2 == null) return l1; ListNode p1 = l1, p2 = l2; ListNode p3, l3; p3 = l3 = new ListNode(0);//注意这里,设一个头节点,方便操作 l3.next = l1; while(p1 != null && p2 != null) { if(p1.val <= p2.val) { p3.next = p1; p3 = p1; p1 = p1.next; } else { p3.next = p2; p3 = p2; p2 = p2.next; } } p3.next = p1==null ? p2 : p1; return l3.next; //因为我们设了一个头节点,所以要跳过头节点 }
结果细节(图):
相关文章推荐
- QT gluPerspective 报错
- SpringMVC学习记录(五)--表单标签
- UML类图符号解释
- 百度定位SDK错误,或者ZXing错误:Couldn't load locSDK3: findLibrary returned null
- 团队介绍 you i
- 基本字符串压缩
- How to install OpenBazaar Server in CentOS7
- 数据结构和算法系列16 哈夫曼树
- eclipse安装hibernate
- C/C++面试题总结(1)
- C#如何对一个类添加拓展方法
- Linux启动Eclipse时指定jdk的三种方法
- 百度云推送相关问题记录
- django 学习 --- 环境搭建
- 设计模式类图概览
- IPv4与IPv6
- 一个小码农的开始
- Bootstrap布局
- 依赖倒置和依赖注入总结
- 最近写的小游戏