Merge Two Sorted Lists
来源:互联网 发布:自学javascript要多久 编辑:程序博客网 时间:2024/06/03 20:00
Problem:
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.
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode h,p,q;
if(l1.val<l2.val) //选择首节点值较小的链表作为主链表
{
h = l1;
p = l1;
q = l2;
}
else
{
h = l2;
p = l2;
q = l1;
}
while(p.next!=null&&q!=null) //把副链表节点插入到主链表
{
if(p.next.val<q.val)
p = p.next;
else
{
ListNode tmp = p.next;
p.next = q;
q = q.next;
p.next.next = tmp;
p = p.next;
}
}
if(p.next==null) //把副链表剩余节点拼接到主链表
p.next = q;
return h;
}
}
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode h,p,q;
if(l1.val<l2.val) //选择首节点值较小的链表作为主链表
{
h = l1;
p = l1;
q = l2;
}
else
{
h = l2;
p = l2;
q = l1;
}
while(p.next!=null&&q!=null) //把副链表节点插入到主链表
{
if(p.next.val<q.val)
p = p.next;
else
{
ListNode tmp = p.next;
p.next = q;
q = q.next;
p.next.next = tmp;
p = p.next;
}
}
if(p.next==null) //把副链表剩余节点拼接到主链表
p.next = q;
return h;
}
}
0 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- 【胡逼蛋砍】——上
- Add Binary
- 输入时间,输入下一秒时间
- html中怎么将标签左对齐,而文本框右对齐的方法
- struts学习之入门级
- Merge Two Sorted Lists
- 数组中的逆序对
- 黑马程序员------object-c面向对象_继承
- 得到
- 区分php的比较运算符:==和===
- html中去掉超链接下划线
- 小白学c++之多线程同步互斥封装
- #ifndef
- Microsoft Research 展示超高精准度的手部追踪技术