回文链表的实现包括以下两个步骤:
1.遍历链表,知道链表的长度,并找到中间节点
注:该步骤需要通过快慢指针实现。上篇博客进行了快慢指针的介绍,请读者查阅。
2.逆至后半段链表,使用两个指针分别从头和中间比较每一半的链表数值;注意链表长度奇偶数。 "或者遍历并用数组记录一遍链表节点数据,再将数组尾到头部与链表相比较,一致则为回文链表。
注:该步骤需要开辟存储空间
详细代码如下:
/* Definition for singly-linked list
struct ListNode
{
int val;
struct ListNode *next;
}; */
typedef struct ListNode Node;
bool isPalindrome(struct ListNode* head) {
if(head==NULL) return true;
Node *fast=head;
Node *slow=head;
Node *p,*q,*temp=NULL;
while(fast->next && fast->next->next) {
fast=fast->next->next;
slow=slow->next;
}
slow=slow->next;
while(slow!=NULL) { //逆置链表
p=slow;
slow=slow->next;
p->next=temp;
temp=p;
}
while(temp!=NULL) { //比较回文
if(temp->val!=head->val)
return false;
temp=temp->next;
head=head->next;
}
return true;
}