leetcode第21题——*Merge Two Sorted Lists

本文介绍了LeetCode第21题的解决方案,详细讲解了合并两个已排序链表的思路,并提供了Python和Java两种语言的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

思路

把两个有序链表归并成一个有序链表。先用比较笨但很简洁的办法:遍历两个有序链表的节点,比较节点值的大小,将较小值放入目标链表中,遍历完后如果两个链表有剩余节点,由于已经是有序的,插入目标链表的最后那个节点即可。

代码

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        cur = head
        
        while(l1 != None and l2 != None):
            #遍历l1和l2的节点并比较大小,将小的放入目标链表中,cur为游标
            if(l1.val < l2.val):
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur.next.next = None
            cur = cur.next
            
        #比较完l1和l2后还有剩余节点
        if(l1 != None):
            cur.next = l1
        else:
            cur.next = l2
            
        return head.next        

Java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head= new ListNode(0);
		ListNode cur = head;
		//遍历l1和l2的节点并比较大小,cur代表当前节点
		while(l1 != null && l2 != null) {
			if(l1.val < l2.val) {
				cur.next = l1;
				l1 = l1.next;
			}
			else {
				cur.next = l2;
				l2 = l2.next;
			}
			cur.next.next = null;//可减少链表大小,提高效率
			cur = cur.next;
		}
		
		//比较完l1和l2的节点后还有剩余节点
		if(l1 != null) cur.next = l1;
		else cur.next = l2;
		
		return head.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值