把链表里的数存入数组
因为数组的定位十分容易,所以把链表里的数依次存入数组中,从数组的第一个数和最后一个数开始,由两头向中间进发,依次比较
bool isPalindrome(struct ListNode* head){
if(!head||!head->next) return true;
int a[999999]={0},i=0,j;
struct ListNode *p=head;
while(p)//把数据存入数组
{
a[i++]=p->val;
p=p->next;
}
for(i=i-1,j=0;j<i;i--,j++)//由两头向中间走
{
if(a[j]!=a[i]) return false;//只要一组不相等,就不是回文数
}return true;
}
效率太差
栈
把链表分为两个部分,前半部分压栈,然后依次出栈与后半部分比较
bool isPalindrome(struct ListNode* head){
if(head==NULL||head->next==NULL) return true;
struct ListNode* p=head;
struct ListNode* q=head;
int i=0;
while(q)
{
i++;//记录节点个数
q=q->next;
}
int m=0,a[999999];
for(m=0;m<(i/2);m++)//前半部分的数存入数组
{
a[m]=p->val;
p=p->next;
}m--;
if(i%2!=0) p=p->next;//奇数项,再往后移一项
while(m>=0)
{
if(a[m]!=p->val)
return false;
m--;
p=p->next;
}
return true;
}
把链表分成两个部分,反转后半部分后与前半部分依次比较
struct ListNode* reverseList(struct ListNode* head){//反转链表
if(head==NULL||head->next==NULL) return head;
struct ListNode *pre=NULL;
while(head)
{
struct ListNode *next=head->next;
head->next=pre;
pre=head;
head=next;
}return pre;
}
bool isPalindrome(struct ListNode* head){
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast&&fast->next)//通过快慢指针找到中点
{
fast=fast->next->next;
slow=slow->next;
}
if(fast) slow=slow->next;//如果fast不为空,说明有奇数项
fast=head;
slow=reverseList(slow);//反转后半部分
while(slow)
{
if(fast->val!=slow->val)//依次比较前半部分和后半部分
return false;
fast=fast->next;
slow=slow->next;
}
return true;
}