很久没写了,连循环中链表要next都忘记了。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类 the head
# @return bool布尔型
#
class Solution:
def isPail(self, head: ListNode) -> bool:
# write code here
newHead = ListNode(0)
p1 = head
# p2 = newHead
cnt = 0
while p1 is not None:
cnt += 1
tmp = ListNode(p1.val)
tmp.next = newHead
p1 = p1.next
newHead = tmp # p2 = p2.next 粗心做错了,因为反转结束后所需要的便是当前节点,不需要记录第一个节点。
for i in range(cnt // 2 + 1):
if head.val != newHead.val:
return False
head = head.next
newHead = newHead.next
return True
评论中采用list数组的方法:
class Solution:
def isPail(self , head: ListNode) -> bool:
# write code here
list1 = []
while head != None:
list1.append(head.val)
head = head.next
print(list1)
left = 0
right = len(list1)-1
while left < right:
if list1[left] != list1[right]:
return False
left += 1
right -= 1
return True
数组的方法中代码最简洁的:
class Solution:
def isPail(self , head: ListNode) -> bool:
res = []
cur = head
while cur:
res.append(cur.val)
cur = cur.next
return res == res[::-1]