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;
    }

优质内容筛选与推荐>>
1、中关村附近银行
2、性能缺陷规范
3、sql中exists,not exists的用法
4、20.Docker Swarm集群
5、C#中类的默认构造函数对类中属性值的初始化情况


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号