Advertisement
korobushk

palindromeLL

May 23rd, 2021
817
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1.    public boolean isPalindrome(ListNode head) {
  2.        
  3.         ListNode slow = head;
  4.         ListNode fast = head;
  5.        
  6.         while(fast!=null&&fast.next!=null){  //middle
  7.             slow=slow.next;
  8.             fast=fast.next.next;
  9.         }
  10.  
  11.         slow = reverseList(slow);    // reverse half
  12.         ListNode newHead = head;
  13.        
  14.         while(slow!=null){
  15.             if(slow.val!=newHead.val){   // check half and half
  16.                 return false;
  17.             }          
  18.             slow= slow.next;
  19.             newHead=newHead.next;          
  20.         }
  21.         return true;
  22.     }
  23.    
  24.    public ListNode reverseList(ListNode head) {
  25.         ListNode prev = null;
  26.         ListNode next = null;
  27.         ListNode curr = head;
  28.         while(curr!=null){
  29.             next=curr.next;
  30.             curr.next=prev;
  31.             prev=curr;
  32.             curr=next;
  33.            
  34.         }
  35.         return prev;
  36.        
  37.     }
  38. }
  39.    
  40.    
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement