力扣打卡第二天

206. 反转链表

在这里插入图片描述

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        // //迭代法
        // ListNode *pre = nullptr;
        // ListNode *curr = head;
        // while(curr){
        //     ListNode *next = curr -> next;
        //     curr -> next = pre;
        //     pre = curr;
        //     curr = next;
        // }
        // return pre;
        //递归
        if(!head || !head -> next){
            return head;
        }
        ListNode *newhead = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = nullptr;
        return newhead;
    }
};

234. 回文链表

在这里插入图片描述

1、快慢指针+翻转(可以实现进阶的要求,也就是说O(1)空间复杂度)

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next)  //表示如果head或者head->next是空的,则返回true
            return 1;
        ListNode *fast = head, *slow = head;
        ListNode *p,*pre = NULL;
        while(fast && fast->next){
            p = slow;
            slow = slow -> next;//慢指针
            fast = fast -> next ->next;//快指针

            p -> next = pre;//翻转
            pre = p;

        }
        if(fast)
            slow = slow -> next;//把慢指针移动到回文开始的地方
        
        while(p){
            if(p->val != slow->val)
                return 0;
            p = p -> next;
            slow = slow -> next;
        }
        return 1;
    }
};

2、栈

        stack<int> s; //定义栈s
        ListNode *p = head;
        while(p){
            s.push(p -> val);//把P的值加入栈s中
            p = p -> next;
        }
        p = head;//把head赋值给P
        while(p){
            if(p -> val != s.top()){
                return 0;
            }
            s.pop();//把栈上面的值pop出去
            p = p -> next;
        }
        return 1;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值