📚博客主页:白日依山璟.
?专栏:《Java》|《数据结构与算法》|《每日一题》
??感谢大家点赞👍🏻收藏?评论?🏻
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4] ,l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [] ,l2 = []
输出:[]
输入:l1 = [] ,l2 = [0]
输出:[0]
newHead
为虚拟节点newHead
就指向谁,头结点就指向头结点的next
newHead
指向头结点的next
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode newHead = new ListNode(-1);
ListNode temp = newHead;
while(list1 != null && list2 != null) {
if (list1.val < list2.val) {
temp.next = list1;
list1 = list1.next;
temp = temp.next;
} else {
temp.next = list2;
list2 = list2.next;
temp = temp.next;
}
}
if (list1 != null) {
temp.next = list1;
}
if (list2 != null) {
temp.next = list2;
}
return newHead.next;
}
}
运行结果:
世界上有三种k,梅花k,方片k,还有任何人不关注我我都会难过的ok