题目描述
Given the head of a singly linked list, return true if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Constraints:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-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:
ListNode* left;
bool recursivelyCheck(ListNode* right) {
if(right == nullptr) return true;
bool res = recursivelyCheck(right->next);
res = res && (left->val == right->val);
left = left->next;
return res;
}
bool isPalindrome(ListNode* head) {
left = head;
return recursivelyCheck(head);
}
};
- 时间复杂度:O(N)。
- 空间复杂度:O(N)。
快慢指针法
/**
* 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:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* next;
while(cur) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
ListNode* p; //p为恢复链表结构作准备
while(fast != nullptr && fast->next != nullptr) {
p = slow;
slow = slow->next;
fast = fast->next->next;
}
if(fast != nullptr) {
p = slow;
slow = slow->next;
}
ListNode* left = head;
ListNode* right = reverseList(slow);
ListNode* q = right;
bool flag = true;
while(right != nullptr) {
if(left->val != right->val) {
flag = false;
}
else
flag = true && flag;
right = right->next;
left = left->next;
}
p->next = reverseList(q);
return flag;
}
};
- 时间复杂度:O(N)。
- 空间复杂度:O(1)。
- 由于翻转链表后半部分破坏了链表的原有结构,故设置p,q来还原链表结构。