除了环形链表,其余都是408做过的
24.两两交换链表的节点
使用虚拟节点,画图
# 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:#必须有cur的下一个和下下个才能交换
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_head.next
递归版本:(没有设置头节点)
# 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]:
if head==None or head.next==None:
return head
pre=head
cur=head.next
temp=head.next.next
#交换
cur.next=pre
pre.next=self.swapPairs(temp)
return cur
19.删除链表的倒数第N个节点
# 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_head=ListNode(next=head)
slow=fast=dummy_head
for i in range(n+1):
fast=fast.next#fast指针走n+1步,只有这样同时移动的时候slow才能指向删除节点的上一个节点(方便做删除操作)
while fast:
fast=fast.next
slow=slow.next
#删除
slow.next=slow.next.next
return dummy_head.next
160.链表相交
# 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:
lenA,lenB=0,0
cur_1=headA
cur_2=headB
while cur_1:
cur_1=cur_1.next
lenA+=1
while cur_2:
cur_2=cur_2.next
lenB+=1#计算长度
len_min=min(lenA,lenB)
len_max=max(lenA,lenB)
cur_1=headA#需要重新定义,因为已经移到了链表的最后
cur_2=headB
for i in range(len_max-len_min):#对齐
if lenA==len_max:
cur_1=cur_1.next
else:
cur_2=cur_2.next
while cur_1 and cur_2:
if cur_1==cur_2:
return cur_1
else:
cur_1=cur_1.next
cur_2=cur_2.next
return None
142.环形链表
. - 力扣(LeetCode)此为判断是否有环
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head # 乌龟和兔子同时从起点出发
while fast and fast.next:
slow = slow.next # 乌龟走一步
fast = fast.next.next # 兔子走两步
if fast is slow: # 兔子追上乌龟(套圈),说明有环
return True
return False # 访问到了链表末尾,无环
快指针至少转了一圈才追上慢指针
n表示转了几圈
慢指针没转完一圈就被快指针追上了
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]:
slow=head
fast=head
while fast and fast.next:
slow =slow.next
fast=fast.next.next
if slow==fast:
slow=head
while slow!=fast:
slow=slow.next
fast=fast.next
return slow
return None