反转类型的题目

滑动窗口

7. 整数反转 - 力扣(LeetCode)

利用迭代的思想,每次循环会得到尾数last,并将传入的num利用/将范围缩小——>因为是倒序我们可以利用结果集*10+last得到最后的结果集

 public int reverse(int num){
        int result=0;
        while(num!=0){
            if(result<Integer.MIN_VALUE/10||result>Integer.MAX_VALUE/10){
                return 0;
            }
            //关键
            int last = num % 10;
            num/=10;
            result=result*10+last;
        }
        return result;
    }

206. 反转链表 - 力扣(LeetCode)

虚拟一个头节点,然后每进一次循环定义一个next后继节点,然后对当前节点进行操作——>cur.next=pre ,pre=cur, cur=next返回pre即可

  public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        //滑动窗口
        while (cur != null) {
            //1.当前节点下一个节点
            ListNode next = cur.next;
            //2,cur指向前面一个节点开始倒叙
            cur.next = pre;
            //3,pre前进一步
            pre = cur;
            //4.cur前一步
            cur = next;
        }
        return pre;
    }

递归解决反转链表

剑指 Offer 24. 反转链表 - 力扣(LeetCode)

1.首先确立base,head.next==null||head==null——>2.进入递归框架直至最后一个节点node(我们这里利用后序的思想)——>3.node只是当前方法中递归返回的节点,也就是个末尾节点——>4.我们利用当前head.next.next=head进行调换位置,当前节点head=null,返回node

 public ListNode reverseList(ListNode head){
        //1.base
        if(head==null||head.next==null){
            return head;
        }
        //2.递归框架
        ListNode node= reverseList(head.next);
        //3.后序位置处理反转逻辑
        head.next.next=head;//两节点指向交换
        head.next=null;
        return node;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fairy要carry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值