判断链表是不是回文数


主要思想,先找到中间结点,对后半段链表反转,然后一一对比数据,看看是不是相同,相同就是回文链表,不同就不是

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:
        temp_next = head.next
        head.next = reverse_head
        reverse_head = head
        head = temp.next
    return revese_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))

        

 

你可能感兴趣的:(判断链表是不是回文数)