Leetcode234 回文链表(递归/反转)

在这里插入图片描述
解决这道题的方法有三种:

  1. 遍历链表得到所有值的数组,用双指针判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( N ) O(N) O(N)
  2. 利用递归判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( N ) O(N) O(N)
  3. 反转链表判断【时间复杂度 O ( N ) O(N) O(N) 空间复杂度 O ( 1 ) O(1) O(1)

附上代码:
递归

class Solution {
    ListNode* comp;
public:
    bool recurr(ListNode* head){
        if(!head) return true;
        bool flag = true;
        if(head->next) flag = recurr(head->next); 
        if(head->val != comp->val) flag = false;
        comp = comp->next;
        return flag; 
    }
    bool isPalindrome(ListNode* head) {
        comp = head;
        return recurr(head);
    }
};

反转链表

class Solution {
    ListNode* comp;
public:
    ListNode* reverseList(ListNode* h){
        ListNode* curr = h;
        ListNode* prev = nullptr;
        while(curr){
            ListNode* t = curr->next;
            curr->next = prev;
            prev = curr;
            curr = t;
        }
        return prev;
    }

    bool isPalindrome(ListNode* head) {
        int n = 0;
        ListNode* temp = head;
        while(temp){temp = temp->next; n++;}
        temp = head;
        //找到分割点
        for(int i=1; i<n/2; i++) temp = temp->next;
        ListNode* h1 = head;
        //构建
        ListNode* h2 = reverseList(temp->next);
        ListNode* h3 = h2;
        if(temp && temp->next)temp->next = nullptr;
        //回文串判断
        bool out = true;  
        while(h1 && h2){
            if(h1->val != h2->val) out = false;
            h1 = h1->next;
            h2 = h2->next;
        }
        //还原链表
        temp->next = reverseList(h3);
        return out;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值