Given a singly linked list, determine if it is a palindrome.
思路:快慢指针,慢指针一次跳一个,快指针一次跳两个,这样快指针跳完慢指针就是中心点
这样还是要用到n/2的栈空间,使用反转链表法可以实现1空间
/**
* 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) {
ListNode slow,fast;
slow=head;
fast=head;
Stack<ListNode> stack=new Stack<ListNode>();
while(fast!=null){
stack.push(slow);
slow=slow.next;
fast=fast.next;
if(fast==null){
stack.pop();
break;
}
fast=fast.next;
}
while(slow!=null){
if(slow.val!=stack.pop().val){
return false;
}
slow=slow.next;
}
return true;
}
}