21、 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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
代码:
public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } static void Main(string[] args) { ListNode l11=new ListNode(1); ListNode l12 = new ListNode(3); ListNode l13 = new ListNode(4); l11.next = l12; l12.next = l13; ListNode l21 = new ListNode(2); ListNode l22 = new ListNode(3); ListNode l23 = new ListNode(5); l21.next = l22; l22.next = l23; var res=MergeTwoSortedLists(l11, l21); while (res != null) { Console.Write(res.val); res = res.next; } Console.ReadKey(); } private static ListNode MergeTwoSortedLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = MergeTwoSortedLists(l1.next, l2); return l1; } else { l2.next = MergeTwoSortedLists(l1, l2.next); return l2; } }
解析:
输入:两个链表
输出:合并后的链表
思想:
三种情况分别讨论,并且用递归的思想。
时间复杂度:O(n)