Problem of the day
You are given a Singly Linked List of integers. You have to return true if the linked list is palindrome, else return false.
A Linked List is a palindrome if it reads the same from left to right and from right to left.
The lists (1 -> 2 -> 1), (3 -> 4 -> 4-> 3), and (1) are palindromes, while the lists (1 -> 2 -> 3) and (3 -> 4) are not.
The first and only line contains the linked list of elements separated by a single space and terminated by -1.
Hence -1 would never be a list element.
Output Format :
Print “True” if the given linked list is a palindrome. Else, print “False”.
Note:
You do not need to print anything.
It has already been taken care of. Just implement the given function.
1 2 2 1 -1
True
The given list is a palindrome.
3 2 1 -1
False
1 <= 'N' <= 5 * 10^4
-10^9 <= 'data' <= 10^9 and 'data' != -1
Where 'N' is the number of nodes in the linked list and ‘data’ represents the value of the list's nodes.
Time Limit: 1sec
Can you think of a data structure which will help you to visit the nodes in reverse?
The idea is to store the list values in a stack and then compare the values in the list with the values in the stack.
Algorithm:
O(N), Where N is the number of nodes in the linked list.
We are traversing the list twice and traversing a list takes O(N) time, thus the final time complexity is O(2 * N) = O(N).
O(N), Where N is the number of nodes in the linked list.
We are storing node values in a stack which will take O(N) extra space.