234.回文链表
主要是单链表不能倒着读,所以放数组里,然后双指针
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
num=[]
p=head
while p!=None:
num.append(p.val)
p=p.next
flag=False
if head!=None:
flag=True
i=0
while i<len(num)//2:
if num[i]!=num[len(num)-1-i]:
flag=False
i+=1
return flag
141. 环形链表
秒了。
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
hashtable=dict()
p=head
flag=False
while p!=None:
if p in hashtable:
flag=True
break
hashtable[p]=1
p=p.next
return flag
142.环形链表2
继续哈希,秒了
python
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
hashtable=dict()
p=head
cnt=0
while p!=None:
if p in hashtable:
return p
hashtable[p]=cnt
p=p.next
cnt+=1
return None