链表之合并两个有序链表

看题目:

leetcode 21 简单

 上代码:

 1 class ListNode:
 2     """节点"""
 3     # 初始化节点
 4     def __init__(self, x):
 5         self.val = x
 6         self.next = None
 7         
 8 class Solution:
 9     def mergelist(self, l1, l2):
10         """
11         :l1 Node
12         :l2 Node
13         """
14         # maintain an unchanging reference to node ahead of the return node
15         # 定义头节点,用于返回合并后的链表
16         head = ListNode(0)
17         
18         # 指向头节点
19         cur = head
20         # 判断两个链表中是否有空链表
21         while l1 is not None and l2 is not None:
22             if l1.val < l2.val:
23                 cur.next, l1 = l1, l1.next
24             else:
25                 cur.next, l2 = l2, l2.next
26             # 移动指针到添加的节点
27             cur = cur.next
28         if l1 is not None:
29             cur.next = l1
30         else:
31             cur.next = l2
32             
33         return head.next
34         

猜你喜欢

转载自www.cnblogs.com/xiaowei2092/p/11720196.html
今日推荐