Tuesday, 31 October 2017

Find out Linked List is Palindrome or not ?

/**
 * Palindrome Linked List (Recursive)
 *
 * @author:http://javainterviewprograms.blogspot.in/
 *
 */
public class Palindrom_LinkedList_Recursive {

          static ListNode left=null;
         
          public static void main(String[] args) {
                  
                   Linked_list ll = new Linked_list();
                   ll.InsertAtEnd(10);
                   ll.InsertAtEnd(20);
                   ll.InsertAtEnd(30);
                   ll.InsertAtEnd(20);
                   ll.InsertAtEnd(10);
                  
                   System.out.println("Is Palindrome:"+IsPalindrome(ll.getStart()));

          }

          private static boolean IsPalindrome(ListNode head) 
       {
                  
                   left = head;
                  
                   return IsPalindromeUtil(head);
          }

          private static boolean IsPalindromeUtil(ListNode head) 
       {
                  
                   if(head == null) return true;
                  
                   boolean b = IsPalindromeUtil(head.getNext()) && (left.getData()                        == head.getData());
                  
                   left = left.getNext();
                  
                   return b;
          }

}

Output:

Is Palindrome:true

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...