Monday, August 18, 2014

LinkedList isPalindrome or not - Java



Implementation:


Or Using Extra space- stack:

:


1 comment:

  1. public static ResultPalindrome isPalindrome(ListNode root1, ListNode root2) {
    if (root1 == null)
    return new ResultPalindrome(root2, true);

    ResultPalindrome res = isPalindrome(root1.next, root2);

    if (!res.isPalindrome)
    return new ResultPalindrome(root2, false);

    if (res.isPalindrome && res.list.value == root1.value) {
    res.list = res.list.next;
    res.isPalindrome = true;
    return res;
    }
    res.isPalindrome = false;
    return res;
    }

    public static boolean isPalindromeLL(ListNode head) {
    if (head == null)
    return true;

    boolean res = true;

    Stack stack = new Stack();
    ListNode slow = head, fast = head;
    for (; fast != null && fast.next != null; slow = slow.next, fast = fast.next.next) {
    stack.push(slow);
    }
    if (fast != null) {
    slow = slow.next;
    }

    while (res && !stack.isEmpty())
    if (res && slow.value == stack.pop().value) {
    slow = slow.next;
    res = true;
    } else
    res = false;

    return res;
    }

    ReplyDelete