真喜欢写链表的题hhh
Q1: 24. Swap Nodes in Pairs
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
left,right = head, head.next
tmp = right.next
right.next = left
left.next = self.swapPairs(tmp)
return right
用时5min
Q2:19. Remove Nth Node From End of List
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
fast, slow = dummy, dummy
for i in range(n):
fast = fast.next
while fast.next != None:
fast = fast.next
slow = slow.next
if slow.next == None:
return None
else:
slow.next = slow.next.next
return dummy.next
用时12min;📢 用dummy node以防要删除的点是head
Q3:142. Linked List Cycle II
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast, slow = head, head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast == None or fast.next == None:
return None
while slow != head:
head = head.next
slow = slow.next
return head
用时10min; 先判断是否有cycle
Q4: 面试题 02.07. Intersection of Two Linked Lists LCCI
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
sA, sB = 0, 0
curA, curB = headA, headB
while curA!= None:
curA = curA.next
sA += 1
while curB!= None:
curB = curB.next
sB += 1
if sB > sA:
headA, headB = headB, headA
for i in range(abs(sA - sB)):
headA = headA.next
while headA != None and headB!= None:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None
用时15min; 出了一个小错,找了一小会。