# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head=ListNode(next = head)
cur = dummy_head
while cur.next and cur.next.next:
temp3=cur.next.next.next
temp1=cur.next
cur.next = cur.next.next
cur.next.next = temp1
temp1.next = temp3
cur = temp1
return dummy_head.next
两两交换链表中的节点,要注意while中的条件,并不是or(分别判断奇偶两种情况)而是and只判断偶数节点的情况,因为奇数节点不需要进行交换
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_node = ListNode(next=head)
slow = fast= dummy_node
for _ in range(n):
fast = fast.next
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy_node.next
删除链表的倒数第 N 个结点,双指针法两个类型,第一个逐渐缩小区域,两指针从两边往中间缩,第二个快慢指针,一个做遍历一个做游标
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
size_a =size_b= 0
cur = headA
while cur:
cur = cur.next
size_a+=1
cur = headB
while cur:
cur = cur.next
size_b+=1
if size_a >=size_b:
_len = size_a - size_b
for _ in range(_len):
headA = headA.next
while headA:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return
else:
_len = size_b - size_a
for _ in range(_len):
headB = headB.next
while headA:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return
链表相交,要注意先判断是否相交,再headA =headA.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_node = ListNode(next = head)
fast = dummy_node
slow = dummy_node
index = dummy_node
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
while index != slow:
slow = slow.next
index = index.next
return index
return
环形链表,直接找个例子带一下就行,不需要数学推导,依旧是快慢指针