Facebook
From Reliable Duck, 5 Years ago, written in Java.
Embed
Download Paste or View Raw
Hits: 190
  1. class Node{
  2.   Node next = null;
  3.   int data;
  4.  
  5.   public Node(int data){
  6.     this.data = data;
  7. }
  8. }
  9.  
  10. class List{
  11.  
  12. Node rev(Node head)
  13.     {
  14.         Node temp = head;
  15.         Node next = null, prev = null;
  16.        
  17.         while(temp != null)
  18.         {
  19.             next = temp.next;
  20.             temp.next = prev;
  21.             prev = temp;
  22.             temp = next;
  23.         }
  24.        
  25.         head =  prev;
  26.        
  27.         return prev;
  28.     }
  29.    
  30.    
  31.    
  32.     Node findMiddle(Node head,int length)
  33.     {
  34.         Node temp2 = head;
  35.         int x = 0;
  36.        
  37.         while(temp2 != null && (x < length/2))
  38.         {
  39.             temp2 = temp2.next;
  40.             x++;
  41.         }
  42.        
  43.         return temp2;
  44.     }
  45.  
  46.    
  47.     int length(Node head)
  48.     {
  49.         Node temp = head;
  50.         int count = 0;
  51.        
  52.         while(temp != null)
  53.         {
  54.             temp = temp.next;
  55.             count++;
  56.         }
  57.        
  58.         return count;
  59.     }
  60.    
  61.     void print(Node head)
  62.     {
  63.           Node temp = head;
  64.           while(temp != null)
  65.         {
  66.             System.out.print(temp.data +" ");
  67.             temp = temp.next;
  68.         }
  69.         System.out.println();
  70.     }
  71.    
  72.    
  73.     boolean isPalindrome(Node head)
  74.     {
  75.        
  76.         Node middle = findMiddle(head,length(head));
  77.         Node secondhead = middle.next;
  78.         middle.next = null;
  79.        
  80.         Node rSecondhead =  rev(secondhead);
  81.        
  82.         while(head != null && rSecondhead != null)
  83.         {
  84.             if(head.data == rSecondhead.data)
  85.             {
  86.                 head = head.next;
  87.                 rSecondhead = rSecondhead.next;
  88.                 continue;
  89.             }
  90.             else return false;
  91.         }
  92.        
  93.         return true;
  94.     }
  95.  
  96. public static void main(String[] args)
  97. {
  98.   List l = new List();
  99.  
  100.   //some test cases
  101. }