设计一种方式检查一个链表是否为回文链表。
样例1->2->1
就是一个回文链表。
挑战
O(n)的时间和O(1)的额外空间。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head||!head->next)
return true;
stack<int> st;
int count=0;
ListNode *ptr=head;
while(ptr){
++count;
ptr=ptr->next;
}
bool open=(count&1)?true:false;
ptr=head;
count/=2;
while(count--){
st.push(ptr->val);
ptr=ptr->next;
}
if(open)
ptr=ptr->next;
while(ptr&&!st.empty()){
if(ptr->val!=st.top())
return false;
st.pop();
ptr=ptr->next;
}
return true;
}
};