📅  最后修改于: 2023-12-03 15:23:04.097000             🧑  作者: Mango
This is a coding problem from ISRO CS 2016 paper. The problem statement is as follows:
Given a linked list of n nodes, the task is to check if the linked list is palindrome or not.
A palindrome linked list will be same if we read the linked list from the beginning and from the end.
We can solve this problem by using a stack data structure. The algorithm is as follows:
The time complexity of this algorithm is O(n), where n is the number of nodes in the linked list, and the space complexity is also O(n) because we are using a stack.
class Node:
def __init__(self, value):
self.value = value
self.next = None
def is_palindrome(head):
stack = []
curr = head
while curr:
stack.append(curr.value)
curr = curr.next
curr = head
while curr:
if curr.value != stack.pop():
return False
curr = curr.next
return True
Here, we define a Node
class to represent a node in the linked list. The is_palindrome
function takes the head of the linked list as input and returns a boolean indicating whether the linked list is a palindrome or not.
We first traverse the linked list and push each element onto the stack. Then, we traverse the linked list again and for each element, pop an element from the stack and compare it with the current element. If they are not equal, we return False indicating that the linked list is not a palindrome. If we reach the end of the linked list, we return True indicating that the linked list is a palindrome.