Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean isPalindrome(ListNode head) {
- ListNode slow = head;
- ListNode fast = head;
- while(fast!=null&&fast.next!=null){ //middle
- slow=slow.next;
- fast=fast.next.next;
- }
- slow = reverseList(slow); // reverse half
- ListNode newHead = head;
- while(slow!=null){
- if(slow.val!=newHead.val){ // check half and half
- return false;
- }
- slow= slow.next;
- newHead=newHead.next;
- }
- return true;
- }
- public ListNode reverseList(ListNode head) {
- ListNode prev = null;
- ListNode next = null;
- ListNode curr = head;
- while(curr!=null){
- next=curr.next;
- curr.next=prev;
- prev=curr;
- curr=next;
- }
- return prev;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement