223. 回文链表
设计一种方式检查一个链表是否为回文链表。
样例
1->2->1
就是一个回文链表。
挑战
O(n)的时间和O(1)的额外空间。
实现思路:
思路一:利用链表进行判断
#使用链表进行判断
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def isPalindrome(self, head):
# write your code here
if head is None or head.next is None:
return True
#找到左半部分
count = 0
cur = head
while cur:
count += 1
cur = cur.next
left = count // 2
#对左半部分进行翻转
dummy = ListNode(0)
pre = dummy
cur = head
while left:
tmp = ListNode(cur.val)
tmp.next = pre.next
pre.next = tmp
left -= 1
cur = cur.next
#对结果做处理,如果链表长度为奇数,则后移一位,跳过中间结点
if count % 2 != 0:
cur = cur.next
#对左右两个部分进行比较,如果出现值不相同,则返回false
while dummy.next and cur:
if dummy.next.val != cur.val:
return False
dummy.next = dummy.next.next
cur = cur.next
return True
思路二:利用数组进行判断
#使用数组来判断
class Solution:
"""
@param head: A ListNode.
@return: A boolean.
"""
def isPalindrome(self, head):
# write your code here
if head is None or head.next is None:
return True
node_list = []
pre = head
while pre:
node_list.append(pre.val)
pre = pre.next
start = 0
end = len(node_list) - 1
while start < end:
if node_list[start] != node_list[end]:
return False
start += 1
end -= 1
return True