
暴力解法:
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:
if head.next==None:
return True
list1 = []
A = head
while(A!=None):
list1.append(A.val)
A = A.next
tou = 0
wei = len(list1)-1
if len(list1)%2==0:
while(tou!=(wei-1)):
if (list1[tou] != list1[wei]):
return False
tou += 1
wei -= 1
if (list1[tou]==list1[wei]):
return True
else:
return False
else:
while(tou!=(wei-2)):
if (list1[tou] != list1[wei]):
return False
tou += 1
wei -= 1
if (list1[tou]==list1[wei]):
return True
else:
return False
官方代码(完全没想到 vals == vals[::-1]):
python
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
vals = []
current_node = head
while current_node is not None:
vals.append(current_node.val)
current_node = current_node.next
return vals == vals[::-1]
作者:力扣官方题解
链接:https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
切片:[start:stop:step]