0
点赞
收藏
分享

微信扫一扫

电子数据取证之宝塔面板

萍儿的小确幸 2023-04-30 阅读 18
🍎道阻且长,行则将至。🍓


一、🌱206. 反转链表

  • 题目描述:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

  • 难度:简单

  • 提示:
    链表中节点的数目范围是 [0, 5000]
    -5000 <= Node.val <= 5000

  • 进阶:链表可以选用迭代递归方式完成反转。你能否用两种方法解决这道题?

🌴解题

反转链表

回顾一下上一题链表题 LeetCode:203. 移除链表元素,介绍了链表的概念、创建链表、删除链表元素。这一题也很简单,把链表指向进行改变。

迭代

迭代法思路很简单,就是一个个遍历处理指针。

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)
        return head;

        ListNode p=head.next,tem;
        head.next=null;
        while(p!=null){
            tem=p.next;
            p.next=head;
            head=p;
            p=tem;
        }
        return head;

    }
}

在这里插入图片描述

递归

递归差不多就是反着来的,思路如下
在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)
        return head;

        ListNode p=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return p;
    }
}

在这里插入图片描述


🌵几处早莺争暖树,谁家新燕啄春泥。 — 钱塘湖春行

返回第一页。☝


🍎☝☝☝☝☝我的CSDN☝☝☝☝☝☝🍓

举报

相关推荐

0 条评论