合并两个排序的链表
合并两个排序的链表
http://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337
思路一:归并排序
public class Solution { public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode head = new ListNode(-1); ListNode list3 = head; while (list1 != null && list2 != null) { if (list1.val < list2.val) { list3.next = list1; list1 = list1.next; } else { list3.next = list2; list2 = list2.next; } list3 = list3.next; } while (list1 != null) { list3.next = list1; list1 = list1.next; list3 = list3.next; } while (list2 != null) { list3.next = list2; list2 = list2.next; list3 = list3.next; } return head.next; } }
思路二:递归
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { if(list1==null) return list2; if(list2==null) return list1; ListNode head = null; if(list1.val<list2.val){ head = list1; head.next=Merge(list1.next,list2); } else{ head = list2; head.next=Merge(list1,list2.next); } return head; } }
----END