首页 > 其他 > 详细

234. Palindrome Linked List

时间:2016-06-16 09:19:19      阅读:263      评论:0      收藏:0      [点我收藏+]
    /*
     * 234. Palindrome Linked List
     * 2016-6-15
     * 这里需要注意的地方就是count开始一定要设为0,然后要判断只有两个值的情况。这个方法很好只有constant的space
     * 还有一个问题就是:奇数个数跟偶数个数要区别对待!!!!
     * count的值也不同
     */
    public static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null)
            return true;
        ListNode slow = head;
        ListNode fast = head;
        int count = 0;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            count++;
        }
        ListNode l1 = null;
        ListNode l2 = null;
        l1 = head;
        if (fast.next == null) {
            l2 = slow.next;
            slow.next = null;
        } else {
            count++;
            l2 = slow.next;
            slow.next = null;
        }
        ListNode ll2 = reverseList(l2);
        while (count != 0) {
            count--;
            if (ll2.val != l1.val) {
                return false;
            }
            l1 = l1.next;
            ll2 = ll2.next;
        }
        return true;
    }

 

234. Palindrome Linked List

原文:http://www.cnblogs.com/zmyvszk/p/5589712.html

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