234. Palindrome Linked List

来源:互联网 发布:2017优化设计政治答案 编辑:程序博客网 时间:2024/06/15 07:46
 public static boolean isPalindrome(ListNode head) {        if((head == null) || (head!=null && head.next == null)) {            return true;        }        int count = 0;        ListNode cur = head;        while(cur != null) {            count++;            cur = cur.next;        }        int needProcess = (count%2 == 0?count/2:count/2+1);        int i = 1;        cur = head;        while(i < needProcess) {            i++;            cur = cur.next;        }        ListNode pre = cur.next,thead = null,tcur = pre.next,tn = null;        pre.next = null;        while(tcur != null) {            tn = tcur.next;            tcur.next = pre;            pre = tcur;            tcur = tn;        }        thead = pre;        boolean is = true;        tcur = head;        while(thead != null && tcur != null) {            if(thead.val != tcur.val) {                is = false;                break;            }            thead = thead.next;            tcur = tcur.next;        }        tcur = pre.next;        pre.next = null;        tn = null;        while(tcur!= null) {            tn = tcur.next;            tcur.next = pre;            pre = tcur;            tcur = tn;        }        cur.next = pre;        return is;    }
0 0