Skip to content

Commit e82195b

Browse files
is linkedlist a palindrome?
1 parent 5e53367 commit e82195b

File tree

1 file changed

+70
-0
lines changed
  • Python/chapter02/2.6 - Palindrome

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/python3
2+
3+
import unittest
4+
5+
6+
class Node:
7+
def __init__(self, data, next=None):
8+
self.data = data
9+
self.next = next
10+
11+
12+
class SinglyLinkedList:
13+
def __init__(self):
14+
self.head = None
15+
16+
def appendNode(self, data):
17+
node = Node(data)
18+
if not self.head:
19+
self.head = node
20+
else:
21+
temp = self.head
22+
while temp.next:
23+
temp = temp.next
24+
temp.next = node
25+
print('Node added to LL-->', data)
26+
27+
def isPalindrome(self):
28+
if not self.head:
29+
print('No LL to traverse')
30+
return
31+
32+
pali = []
33+
temp = self.head
34+
while temp:
35+
pali.append(temp.data)
36+
temp = temp.next
37+
38+
strpali = ''.join(pali)
39+
return strpali == strpali[::-1]
40+
41+
42+
class Test(unittest.TestCase):
43+
@classmethod
44+
def setUpClass(cls):
45+
cls.l = SinglyLinkedList()
46+
cls.l.appendNode('r')
47+
cls.l.appendNode('a')
48+
cls.l.appendNode('c')
49+
cls.l.appendNode('e')
50+
cls.l.appendNode('c')
51+
cls.l.appendNode('a')
52+
cls.l.appendNode('r')
53+
54+
cls.k = SinglyLinkedList()
55+
cls.k.appendNode('n')
56+
cls.k.appendNode('i')
57+
cls.k.appendNode('c')
58+
cls.k.appendNode('k')
59+
60+
@classmethod
61+
def tearDownClass(cls):
62+
pass
63+
64+
def test1(self):
65+
self.assertTrue(self.l.isPalindrome())
66+
self.assertFalse(self.k.isPalindrome())
67+
68+
69+
if __name__ == '__main__':
70+
unittest.main()

0 commit comments

Comments
 (0)