简单

    给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false。 输入:head = [1,2,2,1] 输出:true

    做个数组存一下然后两头挨个比对就可以。因为是单链表,所以想用双指针的方式也不能达到O(n)的时间复杂度。

    1. class Solution {
    2. public:
    3. bool isPalindrome(ListNode* head) {
    4. vector<int> tmp;
    5. while(head){
    6. tmp.push_back(head->val);
    7. head = head->next;
    8. }
    9. for(int i =0,j=tmp.size()-1;i<j;i++,j--){
    10. if(tmp[i] != tmp[j]){
    11. return false;
    12. }
    13. }
    14. return true;
    15. }
    16. };

    时间复杂度O(2n)=O(n),空间复杂度O(n)