LC 24 两两交换链表中的节点:
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next is not None and cur.next.next is not None:
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = temp
temp.next = temp1
cur = cur.next.next
return dummy.next
画图!画图!画图!要不然很容易绕进去,定义虚拟节点事半功倍!
LC19 删除链表的倒数第N个节点:
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
slow, fast = dummy, dummy
while n != 0:
fast = fast.next
n -= 1
while fast.next != None:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next
快慢双指针!要想清楚快指针先走n步,然后快慢指针再同时走,这样当快指针的next指向结尾None时,慢指针刚好在第N-1的位置,然后直接删除第N个节点就行了!
面试题 02.07. 链表相交:
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
cur_a, cur_b = headA, headB
while cur_a != cur_b:
cur_a = cur_a.next if cur_a else headB
cur_b = cur_b.next if cur_b else headA
return cur_a
定义两个节点,从各自链表的头节点开始走,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个 位置相遇!
142.环形链表II:
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if fast == slow:
index1 = fast
index2 = head
while index1 != index2:
index1 = index1.next
index2 = index2.next
return index1
return None
快慢双指针,fast每次两步,slow每次一步。当fast等于slow时说明链表有环,将当前相遇点定义为index1,头节点为index2,两点相遇为入环交点。