解法1: 遍历两个链表,每次选最小的元素作为下一个元素
public class Solution { public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode newHead; if (list1.val <= list2.val) { newHead = list1; list1 = list1.next; } else { newHead = list2; list2 = list2.next; } ListNode prev = newHead; //iterate two lists, select node with smaller val to be the next node; while (list1 != null && list2 != null) { // if list1 is smaller, then next node is list1, and move pointer forward if (list1.val < list2.val) { prev.next = list1; prev = list1; list1 = list1.next; } else { prev.next = list2; prev = list2; list2 = list2.next; } } // after the iterator, must have one list not empty, add it to the end of the result if (list1 == null) { prev.next = list2; } else { prev.next = list1; } return newHead; } }
解法2: 递归
public class Solution { public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode newHead; if (list1.val <= list2.val) { newHead = list1; newHead.next = Merge(list1.next, list2); } else { newHead = list2; newHead.next = Merge(list1, list2.next); } return newHead; } }
解法3: 将链表2插入到链表1中
public class Solution { public ListNode Merge(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode newHead; if (list1.val < list2.val) { newHead = list1; } else { newHead = list2; } ListNode prevOfInsert = new ListNode(0x80000000); prevOfInsert.next = list1; ListNode nextOfInsert = list1; ListNode toBeInsert; while (list2 != null && nextOfInsert != null) { toBeInsert = list2; if (list2.val <= nextOfInsert.val) { list2 = list2.next; prevOfInsert.next = toBeInsert; toBeInsert.next = nextOfInsert; prevOfInsert = toBeInsert; } else { nextOfInsert = nextOfInsert.next; prevOfInsert = prevOfInsert.next; } } // if there are nodes in list2 that greater than the last node of list1, append all list2 to the end if (nextOfInsert == null && list2 != null) { prevOfInsert.next = list2; } return newHead; } }