Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to check if the string or number represented by linked list is palindrome or not
- class LinkedList:
- def __init__(self):
- self.head = None
- # returns True is LinkedList is Empty
- def isEmpty(self):
- if self.head is None:
- return True
- else:
- return False
- # method adds elements to the left of the Linked List
- def addToStart(self, data):
- # create a temporary node
- tempNode = Node(data)
- tempNode.setLink(self.head)
- self.head = tempNode
- del tempNode
- # method adds elements to the right of the Linked List
- def addToEnd(self, data):
- start = self.head
- tempNode = Node(data)
- while start.getNextNode():
- start = start.getNextNode()
- start.setLink(tempNode)
- del tempNode
- return True
- # method displays Linked List
- def display(self):
- start = self.head
- if start is None:
- print("Empty List!!!")
- return False
- while start:
- print(str(start.getData()), end=" ")
- start = start.link
- if start:
- print("-->", end=" ")
- print()
- # node class
- class Node:
- # default value of data and link is none if no data is passed
- def __init__(self, data=None, link=None):
- self.data = data
- self.link = link
- # method to update the data feild of Node
- def updateData(self, data):
- self.data = data
- # method to set Link feild the Node
- def setLink(self, node):
- self.link = node
- # method returns data feild of the Node
- def getData(self):
- return self.data
- # method returns address of the next Node
- def getNextNode(self):
- return self.link
- # checking if linked list is a palindrome and returns a boolean
- def isPalindrome(right, left):
- isPalindrome.left = left
- if right is None:
- return True
- # moving right node to the end of linked list
- if right.getNextNode() is not None:
- right = right.getNextNode()
- isPalindrome(right, isPalindrome.left)
- # comparing left and right nodes
- if isPalindrome.left.getData() == right.getData():
- isPalindrome.left = isPalindrome.left.getNextNode()
- return True
- return False
- # main method
- print("program to check if the given Linked List is a Palindrome or not")
- # creating LinkedList
- myList = LinkedList()
- myList.addToStart(1)
- myList.addToEnd(2)
- myList.addToEnd(3)
- myList.addToEnd(4)
- myList.addToEnd(5)
- myList.addToEnd(6)
- myList.addToEnd(6)
- myList.addToEnd(4)
- myList.addToEnd(3)
- myList.addToEnd(2)
- myList.addToEnd(1)
- myList.display()
- print("Is the Linked List a Palindrome : " + str(isPalindrome(myList.head, myList.head)))
Add Comment
Please, Sign In to add comment