标签:follow list dex fas pac index bool ini 逆序
Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space?
链表的取中+ 逆序, 取中为上取中!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode index = slow.next;
ListNode prev = null;
while (index!= null) {
ListNode temp = index.next;
index.next = prev;
prev = index;
index = temp;
}
while (prev != null) {
if (prev.val != head.val) {
return false;
}
prev = prev.next;
head = head.next;
}
return true;
}
}
标签:follow list dex fas pac index bool ini 逆序
原文地址:http://www.cnblogs.com/apanda009/p/7286279.html