题目链接: 234. 回文链表 - 力扣(LeetCode)
将链表元素放入数组进行判断
数组查找效率较高,而增删效率低;与之相反,链表增删效率低,查找效率慢。而判断回文需要用到大量的查找操作,因此将链表元素放入数组,在数组中用双指针进行操作。
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> num;
ListNode* cur=head;
while(cur){
//在数组中存放链表元素
num.push_back(cur->val);
cur=cur->next;
}
//根据回文的性质,一前一后进行比较
for(int i=0,j=num.size()-1;i<j;i++,j--){
if(num[i]!=num[j]) return false;
}
return true;
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(n) 使用数组存放链表元素
反转链表后半部分加快慢指针
先找到中点,将链表的后半部分反转,然后将链表的前半部分和后半部分依次比较
class Solution {
public:
//找到链表前半部分的最后一个元素
ListNode* half(ListNode* head){
ListNode* slow=head,*fast=head;
while(fast->next!=nullptr&&fast->next->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
//反转链表
ListNode* reverse(ListNode* head){
ListNode* cur=head,*pre=nullptr;
while(cur){
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
bool isPalindrome(ListNode* head) {
ListNode* halfp=half(head);
ListNode* halfnext=halfp->next,*cur=head;
ListNode* halfreverse=reverse(halfnext);
while(halfreverse!=nullptr){
if(cur->val!=halfreverse->val) return false;
cur=cur->next;
halfreverse=halfreverse->next;
}
//恢复链表
halfp->next=reverse(halfreverse);
return true;
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(1)