Skip to content

Commit 1379f45

Browse files
committed
回文链表
1 parent 3659716 commit 1379f45

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

palindrome_linked_list.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param head, a ListNode
5+
# @return a boolean
6+
def isPalindrome(self, head):
7+
# Write your code here
8+
'''
9+
0->1->2->3->2->1->0 => 0->1->2, 3, 2->1->0
10+
0->1->2->3->3->2->1->0 => 0->1->2->3, 3->2->1->0
11+
'''
12+
if head:
13+
list_len = self.listLen(head)
14+
prev, slow, fast = None, head, head # fast每次前进2步
15+
while fast:
16+
fast = fast.next
17+
if not fast:
18+
break
19+
fast = fast.next
20+
prev = slow
21+
slow = slow.next
22+
if list_len == 1:
23+
return True
24+
if (list_len % 2) == 1:
25+
# 长度为奇数
26+
old_tail = prev
27+
new_head = slow.next
28+
else:
29+
old_tail = prev
30+
new_head = prev.next
31+
old_tail.next = None
32+
new_head = self.reverse(new_head)
33+
while head and new_head:
34+
if head.val != new_head.val:
35+
return False
36+
head = head.next
37+
new_head = new_head.next
38+
return True
39+
40+
41+
def reverse(self, head): # 复制,而不是单纯反转。
42+
# write your code here
43+
if not head:
44+
return None
45+
new_head = None
46+
while head:
47+
node = ListNode(head.val)
48+
head = head.next
49+
node.next = new_head
50+
new_head = node
51+
return new_head
52+
53+
def listLen(self, head):
54+
_len = 0
55+
while head:
56+
_len += 1
57+
head = head.next
58+
return _len

0 commit comments

Comments
 (0)