Leetcode 234. 回文链表
思路
将链表所有元素按序放进数组里,再判断是否为回文串。
代码
bool isPalindrome(ListNode* head) {
vector<int> num;
while(head){ //将元素放进数组
num.push_back(head->val);
head=head->next;
}
bool res=true;
int i=0;
int j=num.size()-1; //设置两个指针,分别从前后开始遍历,看是否相等
while(i<j){
if(num[i]==num[j]){
i++;
j--;
}
else{ //只要遇到一个不等的元素就跳出循环
res=false;
break;
}
}
return res;
}
总结
时间、空间复杂度都是O(n)。