Leetcode[234] Palindrome Linked List
程序员文章站
2022-06-09 15:58:48
...
234. Palindrome Linked List
recursion not work, stack will be overflow
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
def check(head):
if not head:
return True
ret=check(head.next) & self.temp.val==head.val
self.temp=self.temp.next
return ret
self.temp=head
return check(head)
using iterative way
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
#find the middle
f=head
s=head
pre=s
if not head or not head.next:
return True
while f and f.next:
f=f.next.next
s=s.next
#reverse the latter half,now we find a middle node, it can be aabaa pattern or acca pattern, here is a trik, mark the middle.next=None,
#b.next=None or c.next=None
pre=None
while s:
t=s.next
s.next=pre
pre=s
s=t
while pre:
if pre.val!=head.val:
return False
pre=pre.next
head=head.next
return True
上一篇: 堆和栈的区别
下一篇: 如何取消两个苹果手机用一个id?
推荐阅读
-
【LeetCode OJ 328】Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
【Leetcode】328.(Medium)Odd Even Linked List
-
[Leetcode] 142. Linked List Cycle II (set / 快慢指针)
-
LeetCode(52)-Remove Linked List Elements
-
Leetcode[234] Palindrome Linked List
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
leetcode 206 反转链表 / reverse linked list
-
Leetcode Flatten Binary Tree to Linked List