原题链接:234. 回文链表
solution:
时间复杂度:O(N),空间复杂度O(n)
利用快慢指针,慢指针只走了一半的链表,在慢指针遍历的同时保存每个节点的值, 当快指针走到链表终点的时候,利用数组元素和当前slow开始比较。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == nullptr || head->next == nullptr) return true;
ListNode *fast = head;
ListNode *slow = head;
vector<int> nums; //保存满指针遍历过的值
while(fast != nullptr && fast->next != nullptr) {
nums.push_back(slow->val);
fast = fast->next->next;
slow = slow->next;
}
if(fast != nullptr) slow = slow->next;
int cnt = nums.size() - 1;
while(slow != nullptr) { //判断后半部分链表和nums中的元素是否相等
if(slow->val != nums[cnt]) return false;
slow = slow->next;
cnt--;
}
return true;
}
};
省去存储数的空间,反转后半部分链表
/**
* 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:
bool isPalindrome(ListNode* head) {
if(head == nullptr || head->next == nullptr) return true;
ListNode *fast = head;
ListNode *slow = head;
vector<int> nums; //保存满指针遍历过的值
while(fast != nullptr && fast->next != nullptr) {
nums.push_back(slow->val);
fast = fast->next->next;
slow = slow->next;
}
if(fast != nullptr) slow = slow->next;
//反转链表
ListNode *pre = nullptr;
while(slow != nullptr) {
ListNode *next = slow->next;
slow->next = pre;
pre = slow;
slow = next;
}
//反转完后pre指向最后一个节点
ListNode *cur = head;
while(pre != nullptr) {
if(pre->val != cur->val) return false;
pre = pre->next;
cur = cur->next;
}
return true;
}
};