一、题目内容
Given a singly linked list, determine if it is a palindrome.
二、代码实现
解法1:
bool isPalindrome(ListNode* head) {
stack<ListNode*> st;
ListNode* start=head;
if(head==NULL)
return true;
while(start!=NULL)
{
st.push(start);
start=start->next;
}
int n=st.size()/2;
start=head;
while(n--)
{
if(start->val==st.top()->val)
{
st.pop();
start=start->next;
}
else
return false;
}
return true;
}
解法2:
int count=0,tmp=0;
ListNode* start=head,*head1,*p,*q;
if(head==NULL || head->next==NULL)
return true;
//
while(start!=NULL)
{
start=start->next;
count++;
}
//middle pointer
tmp=count/2-1;
start=head;
while(tmp--)
{
start=start->next;
}
//
if(count%2)
{
p=start;
start=start->next->next;
p->next=NULL;
}
else
{
p=start;
start=start->next;
p->next=NULL;
}
//reverse
head1=start;
q=start->next;
//
while(q!=NULL)
{
p=q->next;
q->next=start;
start=q;
q=p;
}
head1->next=NULL;
head1=start;
//compare
while(head!=NULL && head1!=NULL)
{
if(head->val!=head1->val)
return false;
head=head->next;
head1=head1->next;
}
return true;