Question: Check the content of singly linked list is palindrome or not.
Example:
Input: 1 -> 2-> 3->4->3->2->1
Output: True
Input: 1 -> 2-> 3->4->5->2->1
Output: False
Solution:
public boolean isPalindrome(ListNode head) {
ListNode slow, fast;
slow=fast=head;
ListNode prev = null;
while(fast!=null && fast.next!=null) {
ListNode next = slow.next;
fast = fast.next.next;
slow.next = prev;
prev = slow;
slow = next;
}
if(fast!=null){
slow = slow.next;
}
while(slow != null) {
if(slow.val != prev.val) {
return false;
}
slow = slow.next;
prev = prev.next;
}
return true;
}
Solution 2: Using Stack
/**
*
Check the content of linked list is palindrome or not
*
* @param l
* @return
*/
public boolean Palindrome(ListNode head)
{
if(l==null){
System.out.println("Empty List");
return false;
}
else {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode slow, fast;
slow=fast=head;
// add first half of list to stack with help of slow and fast pointers
while(slow!=null && fast!=null && fast.next!=null) {
// add to stack
stack.add(slow);
// increment slow pointer one node at a time
slow=slow.next;
// increment fast pointer two nodes at a time
fast=fast.next.next;
}
// add to the stack if fast.next is null to cover odd number of nodes case
if(fast!=null && fast.next==null) {
stack.add(slow);
}
// Compare second half of list with stack values which contains first half
of list
while(!stack.isEmpty()) {
// pop the node from stack
ListNode temp = stack.pop();
// check both the node values
if(slow.element != temp.element) {
return false;
}
// increment slow pointer by one node
slow=slow.next;
}
// return as palindrome if all the nodes matches
return true;
}
}
No comments:
Post a Comment