class Solution {
public:
bool isPalindrome(ListNode* head) {
if(NULL==head||NULL==head->next) return 1;
int len=0;
stack<ListNode*>s;
ListNode *temp,*p=head;
while(p)
{
p=p->next;
len++;
}
ListNode* head1=head;
int i=1;
s.push(head1);
while(i<len/2)
{
head1=head1->next;
s.push(head1);
i++;
}
if(len%2==0) //必须判断奇偶;
{
head1=head1->next;
}
else{
head1=head1->next->next;
}
while(!s.empty())
{
temp=s.top();
s.pop();
if(temp->val==head1->val)
head1=head1->next;
else return 0;
}
return 1;
}
public:
bool isPalindrome(ListNode* head) {
if(NULL==head||NULL==head->next) return 1;
int len=0;
stack<ListNode*>s;
ListNode *temp,*p=head;
while(p)
{
p=p->next;
len++;
}
ListNode* head1=head;
int i=1;
s.push(head1);
while(i<len/2)
{
head1=head1->next;
s.push(head1);
i++;
}
if(len%2==0) //必须判断奇偶;
{
head1=head1->next;
}
else{
head1=head1->next->next;
}
while(!s.empty())
{
temp=s.top();
s.pop();
if(temp->val==head1->val)
head1=head1->next;
else return 0;
}
return 1;
}
};
这个找中点有点慢,如果用双指针的话,fast=fast->next->next; slow=slow->next->next; 更快