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;
    }
}
0 0
原创粉丝点击