Niuke.com High-Frequency Algorithm Question Series-BM4-Merge Two Sorted Linked Lists
Topic description
Input two increasing linked lists, the length of a single linked list is n, merge the two linked lists and make the nodes in the new linked list still in ascending order.
- Data range: 0 <= n <= 1000, -1000 <= node value <= 1000
- Requirements: space complexity O(1), time complexity O(n)
See the original title: BM4 merge two sorted linked lists
Solution 1: Linked List Traversal
- First, judge the special case, if the linked list 1 is empty, directly return the linked list 2; if the linked list 2 is empty, directly return the linked list 1.
Otherwise, first declare a new fake head node, and then traverse linked list one and linked list two, the process is as follows:
- If linked list one is empty, directly connect the remaining nodes of linked list two to the back, and terminate the traversal
- If linked list 2 is empty, directly connect the remaining nodes of linked list 1 to the back, and terminate the traversal
- Otherwise, compare the size of the current node of linked list 1 and linked list 2 to judge the next node, and then process the next node
- Finally, return the merged linked list.
code
public class Bm004 {
/**
* 合并两个排序的链表
*
* @param list1 链表一
* @param list2 链表二
* @return
*/
public static ListNode merge(ListNode list1, ListNode list2) {
// 如果链表一为空,直接返回链表二
if (list1 == null) {
return list2;
}
// 如果链表二为空,直接返回链表一
if (list2 == null) {
return list1;
}
// 声明一个新的假头结点
ListNode newList = new ListNode(-1), next = newList;
// 遍历链表一和链表二
while (list1 != null || list2 != null) {
if (list1 == null) {
// 如果链表一为空,直接将链表二剩下的结点接到后面,并终止遍历
next.next = list2;
break;
} else if (list2 == null) {
// 如果链表二为空,直接将链表一剩下的结点接到后面,并终止遍历
next.next = list1;
break;
} else if (list1.val < list2.val) { // 否则,比较链表一和链表二当前结点的大小,来判断下一个结点,然后处理下一个结点
next.next = list1;
list1 = list1.next;
} else {
next.next = list2;
list2 = list2.next;
}
next = next.next;
}
// 最后,返回合并后的链表
return newList.next;
}
public static void main(String[] args) {
// 1 -> 3 -> 5
ListNode list1 = ListNode.testCase3();
System.out.println("链表一");
ListNode.print(list1);
// 2 -> 4 -> 6
ListNode list2 = ListNode.testCase4();
System.out.println("链表二");
ListNode.print(list2);
ListNode newList = merge(list1, list2);
System.out.println("合并后的链表");
ListNode.print(newList);
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。