判断给定的链表是否是回文链表
Example 1:
Input: 1->2 Output: falseExample 2:
Input: 1->2->2->1 Output: true
进阶:
用时间复杂度为O(n),空间复杂度为O(1)完成
1:将链表中节点的值存入列表中,然后判断列表是否满足回文条件。时间复杂度O(n),空间复杂度O(n)
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
nodeList = []
while head:
nodeList.append(head.val)
head = head.next
for i in range(len(nodeList)//2):
if nodeList[i] != nodeList[len(nodeList)-i-1]:
return False
return True
2:翻转前半部分链表,然后和后半部分链表进行对比,时间复杂度O(n),空间复杂度O(1)(参考他人)
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
prev = None
fast = slow = head
while fast and fast.next: #翻转链表的前n/2个结点,prev为翻转后的头结点
fast = fast.next.next
prev, prev.next, slow = slow, prev, slow.next
if fast: #结点个数为奇数时,跳过最中间的结点
slow = slow.next
while slow and slow.val == prev.val: #前n/2个结点翻转后,与剩下的结点进行对比
prev, slow = prev.next, slow.next
return not prev
算法题来自:https://leetcode-cn.com/problems/palindrome-linked-list/description/
本文介绍两种方法判断链表是否为回文,一种是将链表转换为列表并检查其回文特性,另一种是通过翻转链表的前半部分并与后半部分比较。第一种方法的时间复杂度为O(n),空间复杂度为O(n),第二种方法实现了O(n)的时间复杂度和O(1)的空间复杂度。
659

被折叠的 条评论
为什么被折叠?



