请判断一个链表是否为回文链表。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null || head.next == null){
                return true;
            }
            
            ListNode slow = head;
            ListNode fast = head;
            while(fast!=null && fast.next!=null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            
            
            ListNode pre = null;
           
            if(fast==null) {
                pre = slow;
            }else {
                pre = slow.next;
            }
            
            ListNode cur = pre.next;
            pre.next = null;
            while(cur!=null) {
                ListNode temp = cur.next;
                cur.next = pre;
                pre=cur;
                cur = temp;
            }
            
            while(pre!=null && head!=null){
                if(pre.val != head.val){
                    return false;
                }else{
                 pre=pre.next;
                 head=head.next;
                }
            }
            return true;
            
    }
}

 

posted @ 2019-07-07 10:54  紫色的雪  阅读(557)  评论(0编辑  收藏  举报