合并两个排序的链表
题目:
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
解答:
采用两个指针,分别指向两个链表,每次取较小的,被取的链表头节点后移,直至一方为空:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 ListNode head = new ListNode(0); 12 ListNode node = head; 13 while(l1 != null || l2 != null){ 14 if(l1 == null){ 15 node.next = l2; 16 break; 17 } 18 if(l2 == null){ 19 node.next = l1; 20 break; 21 } 22 if(l1.val < l2.val){ 23 ListNode n = new ListNode(l1.val); 24 node.next = n; 25 l1 = l1.next; 26 }else{ 27 ListNode n = new ListNode(l2.val); 28 node.next = n; 29 l2 = l2.next; 30 } 31 node = node.next; 32 } 33 return head.next; 34 } 35 }