234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up: Could you do it in O(n) time and O(1) space?

//by spliting the linked list

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next==null) return true;

        ListNode slow = head;
        ListNode fast = head.next;

        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
            if(fast != null) fast =fast.next;
        }

        fast = slow.next;
        slow.next = null;

        fast = reverse(fast);
        slow = head;

        while(slow != null && fast != null){
            if(slow.val != fast.val) return false;
            slow = slow.next;
            fast = fast.next;
        }

        return true;
    }

    ListNode reverse(ListNode head){
        ListNode newHead = null;
        while(head != null){
            ListNode tmp = head.next;
            head.next =newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }
}

//recursively

public class Solution {
    ListNode left;

    public boolean isPalindrome(ListNode head) {
        left = head;

        boolean result = helper(head);
        return result;
    }

    public boolean helper(ListNode right){

        //stop recursion
        if (right == null)
            return true;

        //if sub-list is not palindrome,  return false
        boolean x = helper(right.next);
        if (!x)
            return false;

        //current left and right
        boolean y = (left.val == right.val);

        //move left to next
        left = left.next;

        return y;
    }
}

results matching ""

    No results matching ""