题目:判断一个链表是否为回文链表(只有一个节点和没有结点的链表都是回文的)用O(n)时间复杂度和O(1)的空间复杂度解决
思路:通过快慢指针将slow指针遍历至链表中间,遍历过程中,翻转前半部分。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head||!head->next) return true;
ListNode* fast=head,*slow=head;
ListNode* p,*pre=NULL;//用于翻转的模板(翻转前半部分)
while(fast && fast->next){
p=slow;
slow=slow->next;
fast=fast->next->next;
p->next=pre;
pre=p;
}
if(fast) slow=slow->next;//奇数个结点,则跳过中间这个结点
while(slow){
if(slow->val!=pre->val)return false;
slow=slow->next;
pre=pre->next;
}
return true;
}
};
下面为用数组方法(时间复杂度O(n)空间复杂度O(n)),也是最容易想到的办法;
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int>res;
ListNode* temp=head;
while(temp){
res.push_back(temp->val);
temp=temp->next;
}
int size=res.size();
for(int i=0,j=size-1;i<j;i++,j--){
if(res[i]!=res[j])return false;
}
return true;
}
};