1. 程式人生 > >LeetCode 第21題 合並兩個有序鏈表

LeetCode 第21題 合並兩個有序鏈表

兩個 for 通過 有序鏈表合並 merge class ini lin 結點


/*
將兩個有序鏈表合並為一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

Definition for singly-linked list.
public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
*/


 1 class Solution21 {
 2 
 3 
 4   /*
 5     思路:叠代  時間O(n)
6 */ 7 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 8 if (l1 == null) { 9 return l2; 10 } 11 if (l2 == null) { 12 return l1; 13 } 14 15 ListNode newList = new ListNode(0);//headNode 16 ListNode nodePos = newList; 17 18 while (l1 != null && l2 != null
) { 19 /* 20 將list1中結點放入newList 21 */ 22 if (l1.val <= l2.val) { 23 nodePos.next = l1; 24 l1 = l1.next; 25 } else { 26 /* 27 將list2中結點放入newList 28 */ 29 nodePos.next = l2; 30 l2 = l2.next; 31 } 32 nodePos = nodePos.next;
33 } 34 nodePos.next = l1 == null ? l2 : l1; 35 return newList.next; 36 } 37 38 /* 39 思路:遞歸 時間O(n) 40 */ 41 public ListNode mergeTwoLists1(ListNode l1, ListNode l2) { 42 if (l1 == null) { 43 return l2; 44 } 45 if (l2 == null) { 46 return l1; 47 } 48 if (l1.val >= l2.val) { 49 l1.next = mergeTwoLists(l1.next, l2); 50 return l1; 51 } else { 52 l2.next = mergeTwoLists(l1, l2.next); 53 return l2; 54 } 55 } 56 }

LeetCode 第21題 合並兩個有序鏈表