码迷,mamicode.com
首页 > 其他好文 > 详细

Cracking the Coding Interview Q2.7

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

标签:style   blog   color   io   div   new   

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

标签:style   blog   color   io   div   new   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!