Palindrome detection is a common problem in computer science, where a palindrome is a string or sequence of elements that reads the same forwards as it does backwards. This python program addresses the task of checking whether a singly linked list is a palindrome or not.
Problem statement
Given a singly linked list, your goal is to determine whether the list is a palindrome. A singly linked list is considered a palindrome if the sequence of elements remains the same when read from the beginning to the end as well as from the end to the beginning.
Python Program to Check if Singly Linked List is Palindrome
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node else: current = self.head while current.next: current = current.next current.next = new_node def is_palindrome(self): elements = [] current = self.head while current: elements.append(current.data) current = current.next return elements == elements[::-1] # Input: Creating a linked list linked_list = LinkedList() elements = [1, 2, 3, 2, 1] for element in elements: linked_list.append(element) print("Linked List:") current = linked_list.head while current: print(current.data, end=" -> ") current = current.next print("None") if linked_list.is_palindrome(): print("\nThe linked list is a palindrome.") else: print("\nThe linked list is not a palindrome.")
Python
​x
45
1
class Node:
2
def __init__(self, data):
3
self.data = data
4
self.next = None
5
​
6
class LinkedList:
7
def __init__(self):
8
self.head = None
9
10
def append(self, data):
11
new_node = Node(data)
12
if not self.head:
13
self.head = new_node
14
else:
15
current = self.head
16
while current.next:
17
current = current.next
18
current.next = new_node
19
20
def is_palindrome(self):
21
elements = []
22
current = self.head
23
while current:
24
elements.append(current.data)
25
current = current.next
26
return elements == elements[::-1]
27
​
28
# Input: Creating a linked list
29
linked_list = LinkedList()
30
elements = [1, 2, 3, 2, 1]
31
for element in elements:
32
linked_list.append(element)
33
​
34
print("Linked List:")
35
current = linked_list.head
36
while current:
37
print(current.data, end=" -> ")
38
current = current.next
39
print("None")
40
​
41
if linked_list.is_palindrome():
42
print("\nThe linked list is a palindrome.")
43
else:
44
print("\nThe linked list is not a palindrome.")
45
Input / Output
