CC150 :Palindrome List

check 一个List是不是palindrome, 比如 1 -> 2 -> 3 -> 2 -> 1. 
迭代版的要么需要reverse整个list,或者需要借助一个stack来存下前半段,而递归版稍微难一点。
 

 

class Solution {
    class Result {
        public ListNode node;
        public boolean result;
        public Result(ListNode node, boolean result) {
            this.node = node;
            this.result = result;
        }
    }

    public boolean palindromeList(ListNode head) {
        return palindromeList(head, listSize(head)).result;
    }

    private Result palindromeList(ListNode head, int len) {
        if(head == null || len == 0) {
            return new Result(null, true);
        } else if(len == 1) {
            return new Result(head.next, true);
        } else if(len == 2) {
            return new Result(head.next.next, head.data == head.next.data);
        }
        Result res = palindromeList(head.next, len - 2);
        if(!res.result || res.node == null) {
            return result;
        } else {
            return new Result(res.node.next, head.data == res.node.data);
        }
    } 

    private int listSize(ListNode head) {
    int len = 0;

    while(head != null) {
        head = head.next;

        len++;

    }

    return len;
    }
}

 

 

 

posted @ 2015-02-24 11:01  江南第一少  阅读(160)  评论(0)    收藏  举报