forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#85 from zhenchaozhu/develop
python单链表判断是否是回文字符串
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
|
||
|
||
|