#7 Daily Problems -IsListPalindrome
Hey Guys, it’s my 7th day of solving one problem per day continously.This is a very small miles stone I have reached.
Problem:
Note: Try to solve this task in O(n)
time using O(1)
additional space, where n
is the number of elements in l
, since this is what you'll be asked to do during an interview.
Given a singly linked list of integers, determine whether or not it’s a palindrome.
Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l
of the linked list
Example
- For
l = [0, 1, 0]
, the output should beisListPalindrome(l) = true
; - For
l = [1, 2, 2, 3]
, the output should beisListPalindrome(l) = false
.
Input/Output
- [execution time limit] 3 seconds (java)
- [input] linkedlist.integer l
- A singly linked list of integers.
- Guaranteed constraints:
0 ≤ list size ≤ 5 · 105
,-109 ≤ element value ≤ 109
. - [output] boolean
- Return
true
ifl
is a palindrome, otherwise returnfalse
Solution:
// Singly-linked lists are already defined with this interface:// class ListNode<T> {// ListNode(T x) {// value = x;// }// T value;// ListNode<T> next;// }//boolean isListPalindrome(ListNode<Integer> l) {Boolean isPoly = true;ListNode<Integer> firstLinkedList=l;Stack<Integer> slist= new Stack<>();while(firstLinkedList!=null){slist.push(firstLinkedList.value);firstLinkedList= firstLinkedList.next;}while(l!=null){int value=slist.pop();if(value==l.value){isPoly=true;}else{isPoly=false;break;}l=l.next;}return isPoly;}
Hey guys thanks for seeing this and please give some valid suggestion because I will also learn from you.Ok, Let’s meet tomorrow.
Happy coding!
Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!