Leetcode|Palindrome Linked List
阿新 • • 發佈:2018-11-14
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
滿足時間和空間複雜度真得動腦想想啦!
解法1:翻轉整個連結串列,儲存翻轉連結串列,從頭比較。遍歷兩邊了,空間O(n)也不行。
解法2:藉助棧,先找到中點,然後把前半部壓入棧。空間不行。
解法3:找到中點,然後把後半部分原地翻轉。變成了對稱連結串列了!比較就好!空間O(1)。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head||!head->next) return true;
//先找中點
ListNode *pMid=findMiddle(head);
for(ListNode *pNew=reverseList(pMid);head!=pMid;head=head->next,pNew=pNew->next){
if(head->val!=pNew->val) return false;
}
return true;
}
private :
ListNode* reverseList(ListNode* head){
ListNode* p=NULL;
while(head){
ListNode* q=head->next;
head->next=p;
p=head;
head=q;
}
return p;
}
ListNode* findMiddle(ListNode* head){
ListNode *slow= head, *fast=head;
while(fast&&fast->next){
fast=fast->next->next;
slow=slow->next;
}
return slow;//奇數正好在中間,偶數正好在後一段開頭;
}
};