-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathpalindrome.py
109 lines (84 loc) · 2.9 KB
/
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
Problem Statement
Given a singly linked list, we have to check whether it is palindrome or not.
Linked lists is palindrome if it has the same order of elements when traversed forwards and backward.
For example- 1->2->2->1 is palindrome while 1->2->3 is not palindrome
Algorithm:-
1. First find the middle of the linked list using Floyd's Cycle Detection Algorithm.
In this, we travel through the linked list with two pointers, fast pointer is moving twice as fast as the
slow pointer. When the fast pointer reaches the end of the list, the slow pointer must then be in the middle.
2.With slow now at the middle, we can reverse the second half of the list.
Follow the steps to reverse the second half-
Initialize three pointers prev as NULL, curr as slow, and next as NULL.
Iterate through the linked list. In a loop, do the following:
Before changing the next of curr, store the next node
next = curr -> next
Now update the next pointer of curr to the prev
curr -> next = prev
Update prev as curr and curr as next
prev = curr
curr = next
3.Now, set fast to head of linked list and slow to prev(end of linked list) and compare fast->data with slow->data until slow!=NULL.
"""
#LL structure
class Node:
def __init__(self,val):
self.data = val
self.next = None
class Linkedlist:
def __init__(self):
self.head =None
#insert node in LL
def insert(self, val):
newnode = Node(val)
if self.head is None:
self.head = newnode
else:
ptr =self.head
while ptr.next!=None:
ptr=ptr.next
ptr.next = newnode
#display LL
def display(self):
ptr = self.head
while ptr!=None:
print(ptr.data, end="->")
ptr = ptr.next
print()
def checkPalindrome(self):
slow =self.head
fast = self.head
if self.head.next is None:
return True
while(fast!=None and fast.next!=None):
slow=slow.next
fast=fast.next.next
curr=slow
nxt=None
pre=None
while curr!=None:
nxt=curr.next
curr.next=pre
pre=curr
curr=nxt
slow=pre
fast=self.head
while slow!=None:
if slow.data!=fast.data:
return False
slow=slow.next
fast=fast.next
return True
ll = Linkedlist()
print("Enter no. of nodes in linked list")
n = int(input())
lst=[]
print("Enter value of each node")
lst = list(map(int, input().split()))
for i in range(n):
ll.insert(lst[i])
ll.display()
if ll.checkPalindrome():
print("List is Palindrome")
else:
print("List is not Palindrome")