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?
Subscribe to see which companies asked this question
解析:1.链表分为两段,不管是奇数还是偶数;2.第二段反转一下;3.两段对比一下
/**
* 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 pre=new ListNode(-1);
pre.next=head;
ListNode r1=pre;
ListNode slow=pre.next,fast=pre.next;
while(slow!=null&&fast!=null&&fast.next!=null){
pre=pre.next;
slow=slow.next;
fast=fast.next.next;
}
pre.next=null;
ListNode head1=r1.next;;
ListNode head2=reverse(slow);
while(head1!=null&&head2!=null){
if(head1.val!=head2.val) return false;
else{
head1=head1.next;
head2=head2.next;
}
}
return true;
}
private ListNode reverse(ListNode head){
if(head==null||head.next==null) return head;
Stack<ListNode> stack=new Stack<>();
ListNode pre=new ListNode(-1);
ListNode res=pre;
ListNode temp=head;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
while(!stack.isEmpty()){
pre.next=stack.pop();
pre=pre.next;
}
return res.next;
}
}