判断链表回文

题目:

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;
    }
};
相关推荐
夏乌_Wx5 分钟前
练题100天——DAY28:找消失的数字+分发饼干
数据结构·算法
lzh2004091910 分钟前
二叉搜索树与双向链表
数据结构·链表
studytosky35 分钟前
深度学习理论与实战:反向传播、参数初始化与优化算法全解析
人工智能·python·深度学习·算法·分类·matplotlib
WolfGang00732135 分钟前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
努力学算法的蒟蒻1 小时前
day35(12.16)——leetcode面试经典150
算法·leetcode·面试
cccc来财1 小时前
角点检测算法:Harris 和 FAST 方法
算法·计算机视觉·特征提取
风中月隐1 小时前
C语言中以坐标的方式图解“字母金字塔”的绘制
c语言·开发语言·算法·字母金子塔·坐标图解法
q_30238195561 小时前
告别“笨重”检测!VA-YOLO算法让疲劳驾驶识别更轻更快更准
算法·yolo
45288655上山打老虎2 小时前
List容器
数据结构·windows·list
松涛和鸣2 小时前
DAY32 Linux Thread Programming
linux·运维·数据库·算法·list