# 双指针
# 该算法是经典的回文数算法。首先遍历链表,添加所有节点。
# 然后定义左右(头尾)两个指针,对列表进行判断。
# 若相等,范围缩小,若不等,返回即可。
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
while head != None:
stack.append(head.val)
head = head.next
left = 0
right = len(stack) - 1
while left <= right:
if stack[left] == stack[right]:
left += 1
right -= 1
else:
return False
return True
# 栈
# 该算法是回文数算法的另一种解法。依旧首先遍历链表,添加所有节点。
# 然后对列表一半长度进行循环,若与最后一个值相等,弹出即可。
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
while head != None:
stack.append(head.val)
head = head.next
n = len(stack)
if n == 0 or n == 1:
return True
i = 0
while i <= (n // 2 - 1):
if stack[i] == stack[-1]:
stack.pop()
i += 1
else:
return False
return True