题目描述
请判断一个链表是否为回文链表。
示例
输入: 1->2->2->1
输出: true
思路
因为进阶要求空间复杂度为O(1),时间复杂度为O(n),则不能用栈。
用两个指针,一个快指针(走两步),一个慢指针(走一步)。当快指针走到末尾的时候,慢指针的位置就是中间位置,然后原地翻转后序链表。在遍历比较即可。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
auto slow = head, quick = head, pre = head;
while (quick && quick->next) {
pre = slow;
slow = slow->next;
quick = quick->next->next;
}
if (!quick) quick = slow; // 这里分链表长度奇数和偶数情况
else quick = slow->next;
pre->next = nullptr;
// 翻转前面部分的链表
ListNode* newHead = nullptr;
while (head) {
auto next = head->next;
head->next = newHead;
newHead = head;
head = next;
}
// 遍历两个链表
while (newHead && quick){
if (newHead->val != quick->val) return false;
newHead = newHead->next;
quick = quick->next;
}
return true;
}
};