一、题目描述
二、示例
三、难度
简单
四、代码
Java版
4.1 法一:迭代法
时间复杂度O(n+m),依次比较两升序链表结点值
/**
* @author Kidd
* @create 2022-04-23 21:00
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
//final修饰引用类型变量指的是它里面的地址不能变(不能再指向其他变量),但这个地址所指向的对象或数组的内容不可以变(除非用static final)
// 头节点
ListNode mergeList = new ListNode(-1);
ListNode tempList1 = list1, tempList2 = list2, p = mergeList;
//遍历两个升序链表,只要其中一个链表遍历完,则结束
while (tempList1 != null && tempList2 != null) {
if(tempList1.val < tempList2.val) {
p.next = tempList1;
tempList1 = tempList1.next;
}
else {
p.next = tempList2;
tempList2 = tempList2.next;
}
p = p.next;
}
//若有没遍历完的链表,则之间连接tempList1
if(tempList2 != null) {
p.next = tempList2;
}
if (tempList1 != null) {
p.next = tempList1;
}
return mergeList.next;
}
public static void main(String[] args) {
//l1 -> node1 -> node2
ListNode node2 = new ListNode(5);
ListNode node1 = new ListNode(2, node2);
ListNode l1 = new ListNode(1, node1);
//l2 -> n1 -> node2
ListNode n2 = new ListNode(9);
ListNode n1 = new ListNode(7, n2);
ListNode l2 = new ListNode(4, n1);
ListNode merge = new Solution().mergeTwoLists(l1, l2);
while (merge != null) {
System.out.print(merge.val+" ");
merge = merge.next;
}
}
}
4.2 法二:递归法(待更新…)
|