看题目:
思路:
总体思路很简单,就是新建一个链表,逐步将两个链表中的数据按从小到大的顺序(注意:两个链表是已经排好顺序的)依次添加到新的列表中。
上代码:
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