Merge Two Sorted Lists, Leetcode 解题笔记

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.

简单的list处理,比较两个list的第一个node,把小的加到新的list上,注意要hold住新list的head。

/**
 * 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 && l2 == null) return null;
        ListNode head = new ListNode(0);
        ListNode hold = head;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                ListNode temp = l1;
                l1 = l1.next;
                head.next = temp;
                head = head.next;
            }
            else{
                ListNode temp = l2;
                l2 = l2.next;
                head.next = temp;
                head = head.next;
            }
        }
        if(l1 != null){
            head.next = l1;
        }
        else{
            head.next = l2;
        }
        return hold.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s