Leetcode234.回文链表(C语言)
数据结构-链表:算法与数据结构参考
题目:
判断一个链表是否为回文链表。例:
输入: 1->2->2->1
输出: true
思路:
利用快慢指针找到中点,反转后半部分再进行比较
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* head){
//if(head==NULL || head->next==NULL) return NULL;
struct ListNode* pre=NULL;
struct ListNode* next=NULL;
struct ListNode* cur=head;
while(cur){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
bool isPalindrome(struct ListNode* head){
if(head==NULL || head->next==NULL) return true;
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast->next!=NULL && fast->next->next !=NULL){
//两条件缺一不可(反例[1,0,0])
//条件顺序不能颠倒,否则会有用空指针报错
fast=fast->next->next;
slow=slow->next;
} //找到中点
slow=slow->next;
slow=reverse(slow); //将后半部分倒置
while(slow){
if(slow->val != head->val) return false;
slow=slow->next;
head=head->next;
}
return true;
} //比较