fork(4) download
  1.  
  2. class Node {
  3.  
  4. public int data;
  5. public Node next;
  6.  
  7. public Node(int data){
  8. this.data=data;
  9. }
  10.  
  11. public String toString(){
  12. return ""+data;
  13. }
  14. }
  15. /**
  16.  * To check if Linked list is pallindrome or not
  17.  * @author Prateek
  18.  */
  19. class LinkListPallindrome {
  20.  
  21. public boolean checkPallindrome(Node head){
  22. Node n =isPallindrome(head,head);
  23. if(n==null)
  24. return false;
  25. return true;
  26. }
  27.  
  28. public Node isPallindrome(Node head , Node curr){
  29.  
  30. if(curr == null)
  31. return head;
  32.  
  33. Node rval = isPallindrome(head, curr.next);
  34.  
  35. if(rval!=null)
  36. if(rval.data == curr.data)
  37. return rval = (rval.next!=null) ? rval.next : rval;
  38.  
  39. return null ;
  40. }
  41.  
  42. public static void main(String[] args) {
  43.  
  44. Node head= new Node(1);
  45. head.next= new Node(2);
  46. head.next.next= new Node(3);
  47. head.next.next.next= new Node(2);
  48. head.next.next.next.next= new Node(1);
  49.  
  50. LinkListPallindrome obj = new LinkListPallindrome();
  51. System.out.println(obj.checkPallindrome(head));
  52. }
  53. }
  54.  
Success #stdin #stdout 0.06s 380160KB
stdin
Standard input is empty
stdout
true