请判断一个链表是否为回文链表。
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
方法一:反转链表
快慢指针找到中点,然后把中点之后的链表反转。再比对
class Solution
{
private:
ListNode *reverse(ListNode *node)
{
ListNode *pre = nullptr;
ListNode *next = nullptr;
ListNode *cur = node;
while (cur != nullptr)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
public:
bool isPalindrome(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return true;
auto slow = head;
auto fast = head->next;
while (fast != nullptr && fast->next != nullptr)
{
fast = fast->next->next;
slow = slow->next;
}
auto node = reverse(slow->next);
while (node != nullptr)
{
if (head->val != node->val)
return false;
head = head->next;
node = node->next;
}
return true;
}
};
方法二 :递归法
没明白。。。
class Solution
{
private:
ListNode *_node;
bool visit(ListNode *node)
{
if (node== nullptr)
return true;
auto isPal=visit(node->next)&&_node->val == node->val;
_node = _node->next;
return isPal;
}
public:
bool isPalindrome(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return true;
_node = head;
return visit(head);
}
};