📌  相关文章
📜  国际空间研究组织 | ISRO CS 2016 |问题 9(1)

📅  最后修改于: 2023-12-03 15:23:04.097000             🧑  作者: Mango

ISRO CS 2016 Problem 9

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.

Algorithm

We can solve this problem by using a stack data structure. The algorithm is as follows:

  1. Traverse the linked list and push the elements onto the stack.
  2. Traverse the linked list again. For each element, pop an element from the stack and compare it with the current element. If they are not equal, the linked list is not a palindrome.
  3. If the linked list is a palindrome, the stack will be empty after the traversal.

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.

Code
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.