题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
解题思路
无脑版:保存链表的值到列表中,然后就是简单的列表回文串
快慢指针:快指针1次走2个结点,慢指针1次走1个结点,当快指针走到头的时候慢指针指向最中间的结点。慢指针走过的结点入栈,然后再依次比较快指针和慢指针结点栈。
成绩
时间>72.75%
空间>18.58%
代码
无脑版:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
val_list = []
p = head
while p:
val_list.append(p.val)
p = p.next
return val_list == val_list[::-1]
快慢指针版:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow, fast = head, head
slow_stack = []
while fast and fast.next:
slow_stack.append(slow.val)
slow = slow.next
fast = fast.next.next
if fast:
slow = slow.next
while slow:
if slow.val == slow_stack.pop():
slow = slow.next
else:
return False
return True