/** * 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; } }
原文地址:https://www.cnblogs.com/q-1993/p/11145486.html
时间: 2024-10-12 18:40:36