📌  相关文章
📜  Python程序检查字符串的链接列表是否形成回文

📅  最后修改于: 2022-05-13 01:56:56.657000             🧑  作者: Mango

Python程序检查字符串的链接列表是否形成回文

给定一个处理字符串数据的链表,检查数据是否为回文?
例子:

Input: a -> bc -> d -> dcb -> a -> NULL
Output: True
String "abcddcba" is palindrome.

Input: a -> bc -> d -> ba -> NULL
Output: False
String "abcdba" is not palindrome. 

这个想法很简单。从给定的链表构造一个字符串,并检查构造的字符串是否为回文。

Python
# Python program to check if given linked list 
# of strings form a palindrome
  
# Node class 
class Node:
  
    # Constructor to initialize the 
    # node object
    def __init__(self, data):
        self.data = data
        self.next = None
  
class LinkedList:
  
    # Function to initialize head
    def __init__(self):
        self.head = None
  
    # A utility function to check if str 
    # is palindrome or not
    def isPalindromeUtil(self, string):
        return (string == string[::-1])
  
    # Returns true if string formed by 
    # linked list is palindrome
    def isPalindrome(self):
        node = self.head
  
        # Append all nodes to form a string 
        temp = []
        while (node is not None):
            temp.append(node.data)
            node = node.next
        string = "".join(temp)
        return self.isPalindromeUtil(string)
  
    # Utility function to print the 
    # linked LinkedList
    def printList(self):
        temp = self.head
        while (temp):
            print temp.data,
            temp = temp.next
  
# Driver code
llist = LinkedList()
llist.head = Node('a')
llist.head.next = Node('bc')
llist.head.next.next = Node("d")
llist.head.next.next.next = Node("dcb")
llist.head.next.next.next.next = Node("a")
print "true" if llist.isPalindrome() else "false"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)



输出:
true

有关详细信息,请参阅有关检查字符串链接列表是否形成回文的完整文章!