24 两两交换链表中的节点
class Solution(object):
def swapPairs(self, head):
dummy_head = ListNode()
dummy_head.next = head
prev = dummy_head
while prev.next and prev.next.next:
node1 = prev.next
node2 = prev.next.next
node1.next = node2.next
node2.next = node1
prev.next = node2
prev = node1
return dummy_head.next
- 时间复杂度:O(n)
- 空间复杂度:O(1)
19 删除链表的倒数第N个节点
- fast slow
class Solution(object):
def removeNthFromEnd(self, head, n):
dummy_head = ListNode()
dummy_head.next = slow = fast = head
prev = dummy_head
for _ in range(n):
fast = fast.next
while fast:
prev = slow
slow = slow.next
fast = fast.next
prev.next = slow.next
return dummy_head.next
- 时间复杂度:O(n)
- 空间复杂度:O(1)
160 链表相交
class Solution(object):
def getIntersectionNode(self, headA, headB):
stackA = []
stackB = []
if not headA or not headB:
return None
while headA:
stackA.append(headA)
headA = headA.next
headA = stackA.pop()
while headB:
stackB.append(headB)
headB = headB.next
headB = stackB.pop()
while stackA and stackB and headA == headB:
headA = stackA.pop()
headB = stackB.pop()
if not stackA and headA == headB:
return headA
elif not stackB and headA == headB:
return headB
return headA.next
- 时间复杂度:O(n)
- 空间复杂度:O(n)
142 环形链表II
- fast slow
class Solution(object):
def detectCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if not fast or not fast.next:
return None
cur = head
while cur != slow:
cur = cur.next
slow = slow.next
return cur
- 时间复杂度:O(n)
- 空间复杂度:O(1)