Leet Code 21 Merge Two Sorted Lists
2015-09-12 11:05
453 查看
Merge 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
two lists
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // Note: The Solution object is instantiated only once and is reused by each test case. ListNode p,q,r,head; if(l1 == null){ return l2; } if(l2 == null){ return l1; } p = l1; q = l2; head = null; if(p.val <= q.val){ head = p; p = p.next; } else{ head = q; q = q.next; } r = head; while(p != null && q != null){ if(p.val <= q.val){ r.next = p; r = p; p = p.next; } else{ r.next = q; r = q; q = q.next; } } while(q != null){ r.next = q; r = q; q = q.next; } while(p != null) { r.next = p; r = p; p = p.next; } return head; } }
相关文章推荐
- swfit 重载/自定义运算符
- PHP Global变量定义当前页面的全局变量
- Item 26:为什么要推迟变量的定义? Effective C++笔记
- [FromBody]List<string> 用PostMan如何请求
- JAVA-变量
- 如何将一个格林威治字符串时间格式化转换为本地时间
- STL之partial_sum
- c++文件读写
- JPA字段映射(uuid,日期,枚举,@Lob)
- jquery发送手机 验证码倒计时插件 支持页面刷新
- php查找字符是否存在
- redo block header
- 面试常见题
- 《剑指offer》两个链表的第一个公共结点
- Hello 51
- Java HelloWorld
- 如何让Win10开机进入平板模式?开机进入平板模式的方法
- SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意
- Leetcode_232_Implement Queue using Stacks
- log4j additivity 作用