-
Notifications
You must be signed in to change notification settings - Fork 65
/
is_palindrome.py
67 lines (52 loc) · 1.66 KB
/
is_palindrome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
""" check if linked list is palindrome or not
"""
class Node:
""" Node class contains everything related to Linked List node """
def __init__(self, data):
""" initializing single node with data """
self.data = data
self.next = None
class LinkedList:
""" Singly Linked List is a linear data structure """
def __init__(self):
""" initializing singly linked list with zero node """
self.head = None
def insert_head(self, data):
""" inserts node at the start of linked list """
node = Node(data)
node.next = self.head
self.head = node
def print(self):
""" prints entire linked list without changing underlying data """
current = self.head
while current is not None:
print(" ->", current.data, end="")
current = current.next
print()
def is_palindrome(self):
""" removes duplicates from list """
stack = []
current = self.head
while current is not None:
stack.append(current.data)
current = current.next
current = self.head
for _ in range(len(stack)//2):
if stack.pop() != current.data:
return False
current = current.next
return True
def main():
""" operational function """
linkedlist = LinkedList()
linkedlist.insert_head(4)
linkedlist.insert_head(2)
linkedlist.insert_head(2)
linkedlist.insert_head(1)
linkedlist.insert_head(2)
linkedlist.insert_head(2)
linkedlist.insert_head(4)
linkedlist.print()
print(linkedlist.is_palindrome())
if __name__ == '__main__':
main()