学习资料:https://programmercarl.com/0024.两两交换链表中的节点.html
学习记录:
24.两两交换链表中的节点(添加虚拟头节点;交换1、2节点和3、4节点时,要用1前面的cur,先保存1为temp且3保存为temp1,cur指向2,再把2指向temp,因为cur指向2后就与1没关联了)
点击查看代码
# 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:
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
19.删除链表的倒数第N个节点(用快慢指针,fast和slow都设置为虚拟头节点,fast先走N+1步,之后slow和fast同时走,当fast走到NULL,此时slow为倒数第N-1个节点;把slow的下一个节点删除即可)
点击查看代码
# 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
while fast:
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return dummy_head.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]:
fast=slow=head
while fast and fast.next:
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
PS: ● 面试题 02.07. 链表相交 还没做,放一下
阴转雨,吃火锅,爽