将两个排序链表合并为一个新的排序链表
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
这道题很简单,属于链表的基本操作。
只需要创建一个新的链表与一个指向新链表最后一个节点的指针即可。
当 l1
与 l2
均不为空的情况下,判断 l1
和 l2
的大小,把较小值放进新链表的最后一个节点,然后将较小值所处的链表向后移一位,以判断下一个数。
依次循环,直到 l1
或 l2
中有一方为空时,将为空的一方,直接加到新链表后即可。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode lastNode = listNode;
while (l1 != null && l2 != null) {
if (l1.val > l2.val) {
lastNode.next = l2;
l2 = l2.next;
} else {
lastNode.next = l1;
l1 = l1.next;
}
lastNode = lastNode.next;
}
if (l1 == null)
lastNode.next = l2;
if (l2 == null) {
lastNode.next = l1;
}
return listNode.next;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有