典中典之回文,不过是Linked List的回文~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode *head) {
if (head==nullptr || head->next==nullptr) return true;
ListNode *fast = head;
ListNode *slow = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
ListNode *prev = nullptr;
ListNode *succ;
ListNode *cur = slow;
while(cur){
succ = cur->next;
cur->next = prev;
prev = cur;
cur = succ;
}
while(prev->next){
if (prev->val!=head->val)
return false;
prev = prev->next;
head = head->next;
}
return true;
}
};
快慢指针法:快指针到头时慢指针刚好到链表的中间;接着用慢指针遍历后半段并将其倒置;最后比较对称位置的值是否相等。