24. 两两交换链表中的节点
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
需思考的地方:两个临时指针,while的判断条件(and),cur.next 和 cur.next.next的顺序,最后cur=?
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dumy=ListNode(0)
dumy.next=head
cur=dumy
while cur.next and cur.next.next:
t=cur.next
t1=cur.next.next.next
cur.next=cur.next.next
cur.next.next=t
t.next=t1
cur=cur.next.next
return dumy.next
力扣19 删除链表的倒数第N个节点力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
注意:设置dumy的好处:不需要判断是否为空指针,可以采用统一的方式进行操作
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dumy=ListNode(0)
dumy.next=head
fast=dumy
slow=dumy
n=n+1
while n>0:
fast=fast.next
n-=1
while fast:
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return dumy.next
没有使用双指针
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dumy=ListNode(0)
dumy.next=head
cur=dumy
pre=dumy
l=0
while pre.next:
pre=pre.next
l+=1
s=l-n
while s> 0:
cur=cur.next
s-=1
cur.next=cur.next.next
return dumy.next
力扣 面试题02,07 链表相交
注意:if none就会中断 ,判断headA和headB是否为空指针
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A
力扣142 环形链表II
思考:快指针(每次2个节点)为什么不会跳过慢指针(每次1个节点)
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast=head
slow=head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if fast==slow:
p=fast
t=head
while p!=t:
p=p.next
t=t.next
return p
return None