难度简单697
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false示例 2:
输入: 1->2->2->1 输出: true进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
刚开始还是想到用栈
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head) return true;
ListNode* l1 = head;
ListNode* l2 = head;
stack<ListNode*> stk;
while(l1) {
stk.push(l1);
l1 = l1->next;
}
while(!stk.empty() || l2) {
if(l2->val != stk.top()->val) {
return false;
}
l2 = l2->next;
stk.pop();
}
return true;
}
};
题目要求是O(1)的空间复杂度,考虑双指针
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head) return true;
ListNode* fast = head;
ListNode* slow = head;
//快慢指针找链表的中点
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
if(fast) slow = slow->next;
//翻转链表
ListNode* pre = nullptr;
while(slow) {
ListNode* temp = slow->next;
slow->next = pre;
pre = slow;
slow = temp;
}
//pre的链表长度小于等于总链表的一半,pre是否为空作为循环条件
while(pre) {
if(pre->val != head->val) {
return false;
}
head = head->next;
pre = pre->next;
}
return true;
}
};