- Palindrome Linked List My Submissions QuestionEditorial Solution
Total Accepted: 46990 Total Submissions: 166743 Difficulty: Easy
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?
先给出一种时间O(n)空间O(n)的算法,思路就是顺序把值放入到顺序表
然后在顺序表判定回文
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> vals;
while(head!=NULL){
vals.push_back(head->val);
head = head->next;
}
int n = vals.size(),flag=0;
for(int i=0;i<n/2;++i)
if(vals[i]!=vals[n-1-i]){
flag =1;
break;
}
if(flag==1)return false;
else return true;
}
};
给出O(n)空间O(1)的算法,虽然代码长很多,但是省空间啊!!
思想:O->O->O->O->O前半部分逆转,然后中间出发向两端比较
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)return true;
int len=0;
ListNode *p =head;
while(p!=NULL){
len++;
p=p->next;
}
if(len==2)return head->next->val==head->val; //因为逆转的时候是针对大于等于2(2*2就是4)的情况来考虑,所以先处理小于4
if(len==3)return head->val==head->next->next->val;
int i=1;
ListNode *fir=head,*sec=head;
while(i++<len/2)fir=fir->next;
if(len%2==0)sec = fir->next;
else sec = fir->next->next;
if(len>=4){ //逆转前半部分
ListNode *pre_next = fir->next;
ListNode *tmp=head->next,*pretmp = head;
while(tmp!=NULL&&tmp!=pre_next){
ListNode *tmpnext = tmp->next;
tmp->next = pretmp;
pretmp = tmp;
tmp=tmpnext;
}
head->next=NULL;
}
while(fir!=NULL){ //从中间出发判断回文
if(fir->val!=sec->val)return false;
fir = fir->next;
sec = sec->next;
}
return true;
}
};