题目:
回文链表:请判断一个链表是否为回文链表。
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:
利用栈的性质来判断很方便,但是空间复杂度为O(n)。
想一想空间复杂度为O(1) 的方法,之后补充。
程序1:
# 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:
return True
mystack = []
index1 = head
while index1:
mystack.append(index1)
index1 = index1.next
index2 = head
while mystack:
index3 = mystack.pop()
if index2.val == index3.val:
index2 = index2.next
elif index2.val != index3.val:
return False
return True
Leetcode练习(Python):链表类:第234题:回文链表:请判断一个链表是否为回文链表。
原文:https://www.cnblogs.com/zhuozige/p/12813888.html