1.普通版
把链表的每个值存储在数组中,然后从链表两端向中间挨个对比,如果有不等的,就返回false。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head){
//快慢指针?先找到中间位置,然后一个从中间开始,新建一个指针从头开始
struct ListNode* fast=head;
struct ListNode* slow=head;
struct ListNode* begin=head;
if(head==NULL)
{
return true;
}
//普通版
int len=0;
while(begin){
begin=begin->next;
len++;
}
int a[len];
begin=head;
for(int i=0;i<len;i++)
{
a[i]=begin->val;
begin=begin->next;
}
for(int i=0, j=len-1;i<=j;i++,j--){
if(a[i]!=a[j])
{
return false;
}
}
return true;
}
2.进阶版,用o(1)的空间复杂度和o(n)的时间复杂度
直觉告诉我可以用快慢指针,可是我还是没想到怎么搞。
要反转链表,注意在最后一个whle中是判断p,而不是slow,因为slow最终会是NULL,所以一定会返回true。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head){
//快慢指针?先找到中间位置,反转链表,然后一个从中间开始,新建一个指针从头开始
struct ListNode* fast=head;
struct ListNode* slow=head;
struct ListNode* begin=head;
if(head==NULL)
{
return true;
}
//进阶版
// 找到中间节点
while(fast && fast->next){
fast=fast->next->next;
slow=slow->next;
}
// slow=slow->next;
// 反转链表
struct ListNode* p=NULL;
struct ListNode* temp=NULL;
while(slow)
{
temp=slow->next;
slow->next=p;
p=slow;
slow=temp;
}
// 判断,是判断p而不是slow,因为slow最终会到NULL
while(p)
{
if(begin->val != p->val)
{
return false;
}
begin=begin->next;
p=p->next;
}
return true;
}