题目链接:leetcode.
不考虑空间复杂度的话,我只能想到用双端队列
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
执行用时:28 ms, 在所有 C++ 提交中击败了25.16%的用户
内存消耗:13.8 MB, 在所有 C++ 提交中击败了58.07%的用户
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == nullptr)
return true;
deque<int> Q;
ListNode* node = new ListNode(-1);
node -> next = head;
while(head)
{
Q.push_back(head -> val);
head = head -> next;
}
while(Q.size() > 1 && Q.front() == Q.back())//注意[1]
{
Q.pop_back();
Q.pop_front();
}
return Q.size() < 2;
}
};
我好蠢,这个用vector数组不也能实现嘛
还可以递归,,没想到,挺强的,但是依然O(n) O(n)。因为递归堆栈也要时间
/*
执行用时:24 ms, 在所有 C++ 提交中击败了40.91%的用户
内存消耗:15.7 MB, 在所有 C++ 提交中击败了5.06%的用户
*/
class Solution {
ListNode* front;
public:
bool isReverse(ListNode* node)
{
if(node != nullptr)
{
if(!isReverse(node -> next)) return false;
if(node -> val != front -> val) return false;
front = front -> next;
}
return true;
}
bool isPalindrome(ListNode* head) {
front = head;
return isReverse(head);
}
};
想要O(n),O(1),就改变输入,换取空间复杂度
将链表的后半部分反转(修改链表结构),然后将前半部分和后半部分进行比较。比较完成后我们应该将链表恢复原样。虽然不需要恢复也能通过测试用例,但是使用该函数的人通常不希望链表结构被更改。
该方法虽然可以将空间复杂度降到 O(1)O(1),但是在并发环境下,该方法也有缺点。在并发环境下,函数运行时需要锁定其他线程或进程对链表的访问,因为在函数执行过程中链表会被修改。
/*
执行用时:12 ms, 在所有 C++ 提交中击败了95.77%的用户
内存消耗:13.4 MB, 在所有 C++ 提交中击败了81.11%的用户
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if(head == nullptr)
return head;
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur)
{
ListNode* tmp = cur -> next;
cur -> next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head == nullptr)
return true;
//快慢指针找中间
ListNode* slow = head;
ListNode* fast = head;
while(fast -> next && fast -> next -> next)
{
fast = fast -> next -> next;
slow = slow -> next;
}
//反转后半段
ListNode* end = reverseList(slow -> next);
//比较
ListNode* p1 = end;
ListNode* p2 = head;
while(p1)
{
if(p1 -> val != p2 -> val)
return false;
p1 = p1 -> next;
p2 = p2 -> next;
}
//将链表恢复
slow -> next = reverseList(end);
return true;
}
};