1、题目描述:
2、题解:
方法1:辅助栈
思路:
思路:
设置一个栈,先把链表里的结点压到栈里
然后从链表头部遍历:每次出栈,比较,遇到不等时,直接返回False
最后都相等,返回True。
Python代码:
# 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 = []
cur = head
while cur:
stack.append(cur)
cur = cur.next
while head:
if head.val != stack.pop().val:
return False
head = head.next
return True
方法2:双指针+辅助栈
思路:
思路:
快慢指针,找到中间位置
设置一个栈,先把链表里中间位置后面的结点压到栈里
然后从链表头部遍历:每次出栈,比较,遇到不等时,直接返回False
最后都相等,返回True。
Python代码如下:
# 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
slow,fast = head,head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
stack = []
while slow:
stack.append(slow)
slow = slow.next
while stack:
if head.val != stack.pop().val:
return False
head = head.next
return True
方法3:双指针
思路:
思路:
快慢指针,先找到中间位置(奇数在正中间,偶数在中间的前一个位置),并记录
然后把中间位置后面的逆序
然后用两个指针,开始向中间走,有任意结点不等,就返回False
最后返回True,要把逆序的部分改回来
Python代码如下:
# 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 :return True
#找到中间位置
slow,fast = head,head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
#开始反转
second = slow.next #记录右边的链表开头
slow.next = None
while second :
temp = second.next
second.next = slow
slow = second
second = temp
third = slow #记录反转后的头结点
#开始判断匹配
res = True
first = head
while first and third:
if first.val != third.val:
res = False
break
first = first.next
third = third.next
#还原链表
second = slow.next
slow.next = None
while second:
temp = second.next
second.next = slow
slow = second
second = temp
return res
3、复杂度分析:
方法1:
时间复杂度:O(N)
空间复杂度:O(N)
方法2:
时间复杂度:O(N)
空间复杂度:O(N)
方法3:
时间复杂度:O(N)
空间复杂度:O(1)