24. 两两交换链表中的节点
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 递归 head.next = swagPairs(head.next.next)
if head is None or head.next is None:
return head
dummy = ListNode(0, head)
pre = dummy
slow = head
fast = head.next
# 交换
pre.next = fast
slow.next = self.swapPairs(head.next.next)
fast.next = slow
return dummy.next
# while(slow.next and slow.next.next):
# pre = slow
# fast = slow.next.next
# slow = slow.next
# pre.next = fast
# slow.next = fast.next
# fast.next = slow
# print(dummy)
# return dummy.next
19. 删除链表的倒数第N个节点
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# 两个指针,快指针比慢指针快n个,当快指针到头的时候,慢指针就在倒数第n个
# 哑节点
fast, slow = head, head
dummy = ListNode(0, head)
slow_pre = dummy
for i in range(n):
fast = fast.next
while(fast):
fast = fast.next
slow_pre = slow # 暂存slow的前一个
slow = slow.next
slow_pre.next = slow.next
return dummy.next
面试题02.07 链表相交
和leetcode160是一样的:
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
# # 相交的起始节点
# # 链表遍历时间复杂度O(n)
# node_list = []
# head = headA
# # 遍历链表
# while(head):
# node_list.append(head)
# head = head.next
# head = headB
# while(head):
# if head in node_list:
# return head
# head = head.next
# return None
pA = headA
pB = headB
while(pA != pB):
pA = headB if pA == None else pA.next
pB = headA if pB == None else pB.next
return pA
142. 环形链表II
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast = head
slow = head
while(1):
if fast is None:
return
if fast.next is None:
return
fast = fast.next.next
slow = slow.next
if fast == slow:
fast = head
break
while fast != slow:
fast = fast.next
slow = slow.next
return fast