/*
剑指Offer 27. 回文链表
给定一个链表的 头节点 head ,请判断其是否为回文链表。如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
限制:
链表 L 的长度范围为 [1, 105]
0 <= node.val <= 9
进阶:能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
示例:
输入: head = [1,2,3,3,2,1]
输出: true
输入: head = [1,2]
输出: false
*/
/**
* 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;
//找到中间点right
ListNode* right = head;
ListNode* curr = head;
while (curr->next != nullptr && curr->next->next != nullptr) {
curr = curr->next->next;
right = right->next;
}
//将后半段序列逆转
curr = right->next;
ListNode* tmp = curr->next;
right->next = nullptr;
curr->next = right;
while (tmp != nullptr) {
right = curr;
curr = tmp;
tmp = curr->next;
curr->next = right;
}
right = curr;
//判断回文
bool flag = true;
tmp = head;
while (curr != nullptr && tmp != nullptr) {
if (curr->val != tmp->val)flag = false;
curr = curr->next;
tmp = tmp->next;
}
//将序列复原
curr = right->next;//
tmp = curr->next;//
right->next = nullptr;
while (tmp != nullptr) {
curr->next = right;
right = curr;
curr = tmp;
tmp = tmp->next;
}
curr->next = right;
return flag;
}
};
// 200 ms + 115.2 MB
leetcode写题笔记 -- 回文链表
于 2022-03-13 17:07:30 首次发布