判断链表回文

题目:

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;
    }
};
相关推荐
liulilittle1 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
无聊的小坏坏1 小时前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   1 小时前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
秋说2 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
qq_513970442 小时前
力扣 hot100 Day37
算法·leetcode
不見星空2 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack2 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
☆璇3 小时前
【数据结构】栈和队列
c语言·数据结构
DoraBigHead4 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx4 小时前
c语言-指针与一维数组
c语言·开发语言·算法