-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome_linkedlist.py
67 lines (57 loc) · 1.38 KB
/
palindrome_linkedlist.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
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(head, value):
node = Node(value)
if head is None:
head = node
return head
temp = head
while temp.next:
temp = temp.next
temp.next = node
return head
def view(llist):
temp = llist.head
while temp:
print(temp.data)
temp = temp.next
llist1 = LinkedList()
llist1.head = insert(llist1.head, 1)
llist1.head = insert(llist1.head, 2)
llist1.head = insert(llist1.head, 3)
llist1.head = insert(llist1.head, 4)
llist1.head = insert(llist1.head, 2)
llist1.head = insert(llist1.head, 1)
# 123321, 123321
def check_palindrome(llist):
slow = llist1.head
fast = llist1.head
while fast.next:
if fast.next.next == None:
break
slow = slow.next
fast = fast.next.next
temp = slow.next
prev = None
while temp:
next = temp.next
temp.next = prev
prev = temp
temp = next
reversed = LinkedList()
reversed.head = prev
temp1 = reversed.head
temp2 = llist1.head
while temp1:
if temp2.data != temp1.data:
return "not palindrome"
temp1 = temp1.next
temp2 = temp2.next
return ("palindrome")
#view(reversed)
print(check_palindrome(llist1))