首页 > 其他 > 详细

Cracking the Coding Interview Q2.7

时间:2014-07-08 17:15:37      阅读:423      评论:0      收藏:0      [点我收藏+]

检测链表是否是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;
    }

 

Cracking the Coding Interview Q2.7,布布扣,bubuko.com

Cracking the Coding Interview Q2.7

原文:http://www.cnblogs.com/jdflyfly/p/3830700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!