先遍历链表将数据压入栈中,然后再次遍历链表与出栈的数据做对比,如果有不相同的说明不是回文链表。
时间开销O(n) 空间开销O(n)
Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
stack = []
ptr1 = head
while ptr1:
stack.append(ptr1.val)
ptr1 = ptr1.next
ptr2 = head
print(stack)
while len(stack):
tmp = stack.pop()
print(tmp)
if tmp != ptr2.val:
return False
ptr2 = ptr2.next
return True
遍历链表将数据存到数组中,转为简单的回文串问题去解决。
时间开销O(n) 空间开销O(n)
时间开销O(n) 空间开销O(1)
Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# 快慢指针找中心
fast = head
slow = head
while fast:
slow = slow.next
fast = fast.next.next if fast.next else fast.next
# 反转后半段的链表
pre = None
next = None
while slow:
next = slow.next
slow.next = pre
pre = slow
slow = next
ptr = head
while pre:
if pre.val != ptr.val:
return False
ptr = ptr.next
pre = pre.next
return True
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
slow := head
fast := head
for fast!=nil {
slow = slow.Next
if fast.Next != nil {
fast = fast.Next.Next
}else{
fast = fast.Next
}
}
var pre *ListNode
var next *ListNode
for slow != nil {
next = slow.Next
slow.Next = pre
pre = slow
slow = next
}
ptr := head
for pre != nil {
if pre.Val != ptr.Val {
return false
}
pre = pre.Next
ptr = ptr.Next
}
return true
}
原文:https://www.cnblogs.com/leisurelylicht/p/234-hui-wen-lian-biao.html