Merge Two Sorted Lists

题目描述
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.

解题思路
对比两个表头的元素,将较小者插入新的链表中。

源代码
package leetcode;

/*private class ListNode {
     int val;
     ListNode next;
     ListNode(int x) {
         val = x;
         next = null;
     }
}*/

public class MergeTwoSortedLists {
	public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
		//处理空串的情形
		if(l1 == null) return l2;
		if(l2 == null) return l1;
		
		ListNode result = null;
		ListNode lastNode = null;
		if(l1.val <= l2.val){
			lastNode = new ListNode(l1.val);
			l1 = l1.next;
		}
		else{
			lastNode = new ListNode(l2.val);
			l2 = l2.next;
		}
		result = lastNode;
		while(l1 != null && l2 != null){
			ListNode newNode = null;
			if(l1.val <= l2.val){
				newNode = new ListNode(l1.val);
				l1 = l1.next;
			}
			else{
				newNode = new ListNode(l2.val);
				l2 = l2.next;
			}
			lastNode.next = newNode;
			lastNode = newNode;
		}
		if(l1 == null)
			lastNode.next = l2;
		if(l2 == null)
			lastNode.next = l1;
		
        return result;
    }
	
	public static void main(String[] args) {
		ListNode node1 = new ListNode(1); 
		ListNode node2 = new ListNode(2);
		ListNode node3 = new ListNode(3);
		ListNode node4 = new ListNode(4);
		ListNode node5 = new ListNode(5);
		ListNode node6 = new ListNode(6);
		
		ListNode node7 = new ListNode(1); 
		ListNode node8 = new ListNode(2);
		ListNode node9 = new ListNode(3);
		ListNode node10 = new ListNode(4);
		ListNode node11 = new ListNode(5);
		ListNode node12 = new ListNode(6);
		
		node1.next = node2;
		node2.next = node3;
		node3.next = node4;
		node4.next = node5;
		node5.next = node6;
		
		node7.next = node8;
		node8.next = node9;
		node9.next = node10;
		node10.next = node11;
		node11.next = node12;
		
		ListNode l1 = node1;//System.out.println(l1.val);
		ListNode l2 = node7;//System.out.println(l2.val);
		MergeTwoSortedLists mtsl = new MergeTwoSortedLists();
		ListNode result = mtsl.mergeTwoLists(l1, l2);
		while(result != null){
			System.out.print(result.val + " ");
			result = result.next;
		}
	}
}

你可能感兴趣的:(merge)