LeetCode - Merge Two Sorted Lists

        依然是链表的简单操作,把两个链表按大小顺序和成一个链表,但是还是要注意细节。下面是效率不高但是简单易懂的一种解法。需要注意两个链表都为空的情况。

 

 

/**
 * 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;
		if(l1==null && l2!=null)
			return l2;
		if(l1!=null && l2==null)
			return l1;
        ArrayList<Integer> set = new ArrayList<>();
        ListNode p = new ListNode(1), q = new ListNode(1);
        p = l1;
        q = l2;
        while(p != null) {
        	set.add(p.val);
        	p = p.next;
        }
        
        while(q != null) {
        	set.add(q.val);
        	q = q.next;
        }
        Collections.sort(set);
        
        ListNode ans = null;
        ListNode head = new ListNode(1);
        
        for(int i=0; i<set.size(); i++) {
        	
        	if(i == 0) {
        		ans = new ListNode(set.get(i));
        		head = ans;
        	}
        	else {
        		ans.next = new ListNode(set.get(i));
        	    ans = ans.next;
        	}
        	
        	
        }
        
        return head;
        
    }
}

 

posted @ 2015-04-02 23:51  Pickle  阅读(167)  评论(0编辑  收藏  举报