Cracking the Coding Interview Q2.7

检测链表是否是palindrome.

 

思路1:翻转并比较。

思路2:迭代。

思路3:递归。

 

    public static boolean isPalindrome(LinkedListNode head) {
        LinkedListNode fast = head;
        LinkedListNode slow = head;
        
        Stack<Integer> stack = new Stack<Integer>();
        
        while (fast != null && fast.next != null) {
            stack.push(slow.data);
            slow = slow.next;
            fast = fast.next.next;            
        }
        
        /* Has odd number of elements, so skip the middle */
        if (fast != null) { 
            slow = slow.next;
        }
        
        while (slow != null) {
            int top = stack.pop().intValue();
            System.out.println(slow.data + " " + top);
            if (top != slow.data) {
                return false;
            }
            slow = slow.next;
        }
        return true;
    }



public Question.Result isPalindromeRecurse(LinkedListNode head, int length) {
        if (head == null || length == 0) {
            return new Question.Result(null, true);
        } else if (length == 1) {
            return new Question.Result(head.next, true);
        } else if (length == 2) {
            return new Question.Result(head.next.next, head.data == head.next.data);
        }
        Question.Result res = isPalindromeRecurse(head.next, length - 2);
        if (!res.result || res.node == null) {
            return res; // Only "result" member is actually used in the call stack.
        } else {
            res.result = head.data == res.node.data;
            res.node = res.node.next;
            return res;
        }
    }
    
    public boolean isPalindrome(LinkedListNode head) {
        int size = 0;
        LinkedListNode n = head;
        while (n != null) {
            size++;
            n = n.next;
        }
        Result p = isPalindromeRecurse(head, size);
        return p.result;
    }

 

posted @ 2014-07-08 00:23  jdflyfly  阅读(172)  评论(0编辑  收藏  举报