今天搞链表
参考链接:力扣
以上是截了大佬的图
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast=head
low=head
while(fast!=None and fast.next!= None):
fast=fast.next.next
low=low.next
if fast==low:
return True
return False
python里空是用None,而不是null
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow,fast=head,head
while(fast!=None and fast.next!=None):
fast=fast.next.next
slow=slow.next
if fast==slow:
break
if (fast==None or fast.next==None):#判断是否有环
return None
fast=head
while(fast!=slow):
fast=fast.next
slow=slow.next
return fast
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if (headA==None or headB==None):
return None
p1,p2=headA,headB
while(p1!=p2):
if p1==None:
p1=headB
else:
p1=p1.next
if p2==None:
p2=headA
else:
p2=p2.next
return p1
太神奇了,这道题的思路在于让A走一遍b的路,让B走一遍A的路
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
#nums.sort(key=bool,reverse=True)
last=cur=0
for i in range(len(nums)):
if nums[i]!=0:
nums[last]=nums[i]
last+=1
i+=1
for i in range(last,len(nums)):
nums[i]=0
return nums
累了 我好菜