判断给定的链表是否是回文链表
Example 1:
Input: 1->2 Output: false
Example 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/