LeetCode 21 _ 合并两个有序链表
1. 题目描述
2. 代码
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 8 prehead = ListNode(-1) 9 prev = prehead 10 while l1 != None and l2 != None: 11 if l1.val <= l2.val: 12 prev.next = l1 13 l1 = l1.next 14 else: 15 prev.next =l2 16 l2 = l2.next 17 prev = prev.next 18 if l1 is not None: 19 prev.next = l1 20 else: 21 prev.next = l2 22 return prehead.next
思路: 如下图
3. 语法整理: 数据结构中的链表
3.1 创建链表及单链表遍历
1 class ListNode: 2 def __init__(self, val=0, next=None): 3 self.val = val 4 self.next = next 5 if __name__ == '__main__': 6 l1 = ListNode(1) 7 l2 = ListNode(2) 8 l3 = ListNode(3) 9 10 l1.next = l2 11 l2.next = l3 12 13 #单链表遍历 14 while l1 != None: 15 print(l1.val) 16 l1 = l1.next
1 2 3
3.2 头插法
1 class ListNode: 2 def __init__(self, val=0, next=None): 3 self.val = val 4 self.next = next 5 6 ary = [1,2,3] 7 prehead = ListNode(-1) 8 prev = prehead 9 10 #头插法 11 for i in range(len(ary)): 12 curval = ary[i] 13 li = ListNode(curval) 14 prev.next = li 15 prev = prev.next