判断链表回文

题目:

cpp 复制代码
//方法一,空间复杂度O(n)
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> nums;      //放进数组后用双指针判断
        ListNode* cur = head;
        while(cur){
            nums.emplace_back(cur->val);
            cur = cur->next;
        }
        for(int i=0, j=nums.size()-1; i < j; i++, j--){
            if(nums[i]!=nums[j]) return false;
        }
        return true;
    }
};
//方法二,空间复杂度O(1)
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head) return true;
        ListNode* end = findend(head);
        ListNode* head1 = reverseList(end->next);
        ListNode* cur1 = head;
        ListNode* cur2 = head1;
        while(cur1&&cur2){
            if(cur1->val!=cur2->val) return false;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        end->next = reverseList(head1);  //恢复链表
        return true;
    }
    //寻找链表前半部分的末尾节点
    ListNode* findend(ListNode* head){
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast->next&&fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
  //翻转链表
   ListNode* reverseList(ListNode* head){
        ListNode* pre = nullptr;
        ListNode* cur = head;
        ListNode* tmp;
        while(cur){
            tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};
相关推荐
今禾31 分钟前
一行代码引发的血案:new Array(5) 到底发生了什么?
前端·javascript·算法
橙几41 分钟前
击败了90%的解法?Two Sum 从 O(n²) 到 O(n) 的优化之路
算法
叶子爱分享1 小时前
经典排序算法之归并排序(Merge Sort)
算法·排序算法
珹洺1 小时前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
呆呆的小鳄鱼2 小时前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香2 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely2 小时前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07122 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_2 小时前
cf1925B&C
数据结构·算法
YuTaoShao2 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先