We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent ae36f93 commit 027cfc7Copy full SHA for 027cfc7
linkedlist/palindrome.py
@@ -0,0 +1,40 @@
1
+# 234. Palindrome Linked List
2
+
3
+# Given a singly linked list, determine if it is a palindrome.
4
+# Time: O(n)
5
+# Space: O(1)
6
7
+# 思路:
8
+# 设置快慢pointer,当快的pointer指向最后的时候,慢的正好是中间
9
+# 以中间的Node为起始,开始reverse后半边的链表
10
+# 从Head和Tail开始往中间循环,比对
11
12
+class Solution(object):
13
+ def isPalindrome(self, head):
14
+ """
15
+ :type head: ListNode
16
+ :rtype: bool
17
18
+ slow = fast = head
19
20
+ while fast and fast.next:
21
+ fast = fast.next.next
22
+ slow = slow.next
23
24
+ prev = None
25
26
+ #Reverse here
27
+ while slow:
28
+ nxt = slow.next
29
+ slow.next = prev
30
+ prev = slow
31
+ slow = nxt
32
33
+ tail = prev
34
35
+ while head and tail:
36
+ if head.val != tail.val:
37
+ return False
38
+ head = head.next
39
+ tail = tail.next
40
+ return True
0 commit comments