编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head){
struct ListNode* f,*l,*b,*t;
f = head; //快指针
l = head; //慢指针
b = NULL;
while(f&&f->next!=NULL){ //反转后半段链表
t = l;
l = l->next;
f = f->next->next;
t->next = b;
b = t;
}
if(f!=NULL){ //链表为奇数的情况
l = l->next;
}
while(t&&l){
if (t->val==l->val){
t = t->next;
l = l->next;
}
else return false;
}
return true; //包含了head||head->next不存在的情况
}
找见中间点是关键,要反转后半段链表,还要考虑链表奇数偶数的问题。
用快慢指针找中间点,速度差为1。