用到快慢指针!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.ne服务器托管xt == null)return true;//空链表和一个节点链表也是回文链表
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode newHead = slow.next;
slow.next = null;
ListNode newFastHead = reverseList(newHead);
ListNode right = newFastHead;
ListNode left = head;
while (right != null){
if(right.val != left.val){
return false;
}
left = left.next;
right = right.next;
}
return true;
}
public ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode curr = head;
while (curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net