题目链接
题目描述
给定一个链表的 头节点 head ,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
示例 1:
输入: head = [1,2,3,3,2,1]
输出: true
示例 2:输入: head = [1,2]
输出: false
提示:
链表 L 的长度范围为 [1, 105]
0 <= node.val <= 9
进阶:能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解题思路
通过快慢指针找重点,通过栈匹配回文
代码
Python
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
slow, fast = head,head
stack = []
while fast.next != None and fast.next.next != None:
stack.append(slow.val)
slow = slow.next
fast = fast.next.next
if fast.next != None and fast.next.next == None:
stack.append(slow.val)
slow = slow.next
while slow != None:
if stack.pop() != slow.val:
return False
slow = slow.next
return True
Go
type Stack []int
func (s *Stack) push(a int) {
*s = append(*s, a)
}
func (s *Stack) pop() (int, error) {
if len(*s) == 0 {
return 0, errors.New("Empty Stack")
}
a := *s
defer func() {
*s = a[:len(a)-1]
}()
return a[len(a)-1], nil
}
func (s *Stack) isEmpty() bool {
if len(*s) == 0 {
return true
}
return false
}
func isPalindrome(head *ListNode) bool {
slow, fast := head, head
var stack Stack
for fast.Next != nil && fast.Next.Next != nil {
stack.push(slow.Val)
slow = slow.Next
fast = fast.Next.Next
}
if fast.Next != nil && fast.Next.Next == nil {
stack.push(slow.Val)
}
slow = slow.Next
for slow != nil {
a, _ := stack.pop()
if slow.Val != a {
return false
}
slow = slow.Next
}
return true
}