classListNode(object): def__init__(self, x): self.val = x self.next = None
TIP: 有时候不太理解指针变化可以使用画图举例法,将指针变化通过画图更直观的呈现出来
合并两个有序链表
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defmerge_wwo_lists(self, l1, l2): cur = ans = ListNode(0) while l1 and l2: if l1.val > l2.val: cur.next = l2 l2 = l2.next else: cur.next = l1 l1 = l1.next cur = cur.next cur.next = l1 or l2 return ans.next
环形链表
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: defhas_cycle(self, head: ListNode) -> bool: """ 如果是环形链表,一快一慢的双指针最终会相遇 """ ifnot head ornot head.next: # 防止head为空或只为一个值 returnFalse fast = head.next # 快指针 slow = head # 慢指针 while fast != slow: ifnot fast ornot fast.next: returnFalse fast = fast.next.next slow = slow.next returnTrue
单链表反转
1 2 3 4 5 6 7 8 9 10
classSolution(object): defreverse_list(self, head): cur, ans = head, None while cur: temp = cur.next cur.next = ans ans = cur cur = temp # ans, ans.next, cur = cur, ans, cur.next return ans
链表的中间结点
1 2 3 4 5 6 7
classSolution: defmiddle_node(self, head): fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next return slow
删除链表倒数第 n 个结点
1 2 3 4 5 6 7 8 9 10 11
classSolution: defremove_nth_from_end(self, head: ListNode, n: int) -> ListNode: node = ListNode(0) node.next = head left = right = node for _ in range(n+1): right = right.next while right: left, right = left.next, right.next left.next = left.next.next return node.next