方法一:将值复制到数组中然后用双指针
时间复杂度:O(n)
空间复杂度:O(n)
class Solution
{
public:
bool isPalindrome(ListNode* head)
{
vector<int> v;
for (ListNode* temp = head; temp != nullptr; temp = temp->next)
{
v.push_back(temp->val);
}
auto Itr = v.begin();
auto rItr = v.rbegin();
for (int i = 0; i < (v.size()) / 2; i++, Itr++, rItr++)
{
if (*Itr != *rItr)
{
return false;
}
}
return true;
}
};
方法二:快慢指针
逆序后半部分链表然后比较
时间复杂度:O(n)
空间复杂度:O(1)
class Solution
{
public:
ListNode* reverseList(ListNode* head) //反转链表
{
if (head == nullptr)
{
return head;
}
else if (head->next == nullptr)
{
return head;
}
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr)
{
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
bool isPalindrome(ListNode* head)
{
ListNode* fast = head; //回文链表一定是对称的
ListNode* slow = head;
while (fast != nullptr && fast->next != nullptr)
{
fast = fast->next->next; //所以先通过快慢指针找到链表中间的节点
slow = slow->next;
}
//然后将后半段链表逆序
if (fast == nullptr) //这里说明链表节点个数为偶数
{
slow = reverseList(slow);
}
else
{
slow->next = reverseList(slow->next);
slow = slow->next;
}
for (ListNode* first = head, *second = slow;
second != nullptr;
first = first->next, second = second->next)
{
if (first->val != second->val) //一个一个比较
{
return false;
}
}
return true;
}
};
方法三:递归
时间复杂度:O(n)
空间复杂度:O(n)
class Solution
{
private:
ListNode* ptr; //需要另外一个指针
public:
bool check(ListNode* curr)
{
if (curr != nullptr)
{
if (check(curr->next) == false)
{
return false;
}
if (ptr->val != curr->val)
{
return false;
}
ptr = ptr->next;
}
return true;
}
bool isPalindrome(ListNode* head)
{
ptr = head;
return check(head);
}
};