Skip to content

Commit

Permalink
Merge pull request wangzheng0822#85 from zhenchaozhu/develop
Browse files Browse the repository at this point in the history
python单链表判断是否是回文字符串
  • Loading branch information
wangzheng0822 authored Oct 23, 2018
2 parents d331c55 + 30c46e3 commit fb3fdc1
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions python/06_linkedlist/palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""
check a single-linked list whether a palindrome
"""

import sys
# 引用当前文件夹下的single_linked_list
sys.path.append('singly_linked_list')
from singly_linked_list import SinglyLinkedList

def reverse(head):
reverse_head = None
while head:
next = head._next
head._next = reverse_head
reverse_head = head
head = next

return reverse_head

def is_palindrome(l):
l.print_all()
slow = l._head
fast = l._head
position = 0
while fast and fast._next:
slow = slow._next
fast = fast._next._next
position += 1

reverse_node = reverse(slow)
head_node = l._head
is_palin = True
while (head_node and reverse_node):
if (head_node.data == reverse_node.data):
head_node = head_node._next
reverse_node = reverse_node._next
else:
is_palin = False
break

return is_palin

if __name__ == '__main__':
# the result should be False, True, True, True, True
test_str_arr = ['ab', 'aa', 'aba', 'abba', 'abcba']
for str in test_str_arr:
l = SinglyLinkedList()
for i in str:
l.insert_value_to_head(i)

print(is_palindrome(l))



0 comments on commit fb3fdc1

Please sign in to comment.