Python合并两个链表

感受python语言的优美的写法:


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
	def combine(self,list2, list3):

		if list2==None:
			return list3

		if list3==None:
			return list2

		dummy  = ListNode(-1)
		temp = dummy

		while list2!=None and list3!=None:
			if list2.val<=list3.val:
				temp.next = list2
				list2 = list2.next
				temp = temp.next
			else:
				temp.next = list3
				list3 = list3.next
				temp = temp.next

		if list2!=None:
			temp.next = list2

		if list3!=None:
			temp.next = list3

		return dummy.next


if __name__ == "__main__":

	node1 = ListNode(2)
	node2 = ListNode(3)
	node3 = ListNode(4)

	node1.next = node2
	node2.next = node3
	node3.next = None

	h2 = ListNode(3)
	h3 = ListNode(4)
	h4 = ListNode(8)

	h2.next = h3
	h3.next = h4
	h4.next = None

	s = Solution()
	res = s.combine(node1, h2)

	while res:
		print(res.val, end=" ")
		res = res.next

 

### 合并两个链表Python实现 在Python中,可以通过多种方法来实现两个链表合并操作。以下是几种常见的实现方式: #### 方法一:迭代法 通过创建一个新的链表,并逐步遍历输入的两个链表中的节点,按照从小到大的顺序依次加入新的链表。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1, l2): # 创建一个哑节点(dummy node),用于简化边界条件处理 dummy = ListNode(0) current = dummy # 当两个链表均未遍历时,执行循环 while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next # 将剩余部分直接连接到新链表末尾 current.next = l1 if l1 is not None else l2 # 返回合并链表的第一个有效节点 return dummy.next ``` 这种方法的时间复杂度为 \(O(n + m)\)[^3],其中 \(n\) 和 \(m\) 是两个链表的长度。空间复杂度为 \(O(1)\) 因为其只使用了常数级别的额外存储空间[^4]。 --- #### 方法二:递归法 利用递归来解决此问题的核心思想是每次比较两个链表头部节点的值,选取较小的一个作为当前节点,并将其余部分继续递归合并。 ```python def mergeTwoListsRecursive(l1, l2): if not l1: return l2 elif not l2: return l1 elif l1.val < l2.val: l1.next = mergeTwoListsRecursive(l1.next, l2) return l1 else: l2.next = mergeTwoListsRecursive(l1, l2.next) return l2 ``` 该方法同样具有时间复杂度 \(O(n + m)\)[^4] 的特性,但由于其依赖于函数调用栈,因此空间复杂度会达到 \(O(n + m)\)。 --- #### 示例测试代码 为了验证以上两种方法的有效性,下面提供了一组简单的测试数据及其运行结果展示。 ```python # 辅助函数:打印链表内容 def printList(node): result = [] while node: result.append(str(node.val)) node = node.next print(" -> ".join(result)) if __name__ == "__main__": # 构建第一个链表: 1 -> 8 -> 11 list1 = ListNode(1, ListNode(8, ListNode(11))) # 构建第二个链表: 3 -> 4 -> 5 list2 = ListNode(3, ListNode(4, ListNode(5))) # 使用迭代法合并链表 merged_iterative = mergeTwoLists(list1, list2) print("Iterative Merge Result:") printList(merged_iterative) # 使用递归法重新构建链表 (注意原链表已被修改需重建) list1_rebuild = ListNode(1, ListNode(8, ListNode(11))) list2_rebuild = ListNode(3, ListNode(4, ListNode(5))) merged_recursive = mergeTwoListsRecursive(list1_rebuild, list2_rebuild) print("\nRecursive Merge Result:") printList(merged_recursive) ``` **预期输出** ``` Iterative Merge Result: 1 -> 3 -> 4 -> 5 -> 8 -> 11 Recursive Merge Result: 1 -> 3 -> 4 -> 5 -> 8 -> 11 ``` --- ### 性能对比与适用场景 - **迭代法** 更适合内存受限环境下的应用,因为它不需要额外的堆栈开销。 - **递归法** 则更简洁直观,在某些特定情况下可能更容易理解和维护,但需要注意潜在的栈溢出风险。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值