当前位置: 首页 > article >正文

代码随想录:206. 反转链表

206. 反转链表

创建头结点,使用头插法,并用新的结点保存值插入里面。
空间复杂度O(n2)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode h=new ListNode();
        while(head!=null)
        {
            ListNode t= new ListNode(head.val,head.next);
            head=head.next;
            t.next=h.next;
            h.next=t;
        }
        return h.next;
    }
}

空间复杂度O(1)

如果我们用变量把下一个位置保存起来,就可以对当前位置随意更改了,原地更改后,更新遍历指针即可。这里我采用head遍历,t临时存放下一个位置

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode h=new ListNode();
        ListNode t=null;
        while(head!=null)
        {
           t=head.next;
           head.next=h.next;
           h.next=head;
           head=t;
        }
        return h.next;
    }
}

递归

cur存已经反转好的后面的链表,head.next指向的为末尾的,把自己接上即可,再把尾巴置null。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)
        return head;
        ListNode cur=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return cur;
    }
}

http://www.kler.cn/news/363764.html

相关文章:

  • V2X介绍
  • nginx的配置
  • volatile 关键字的作用学习
  • mysql 视图中用变量实现 自动加入序号
  • 专业第三方的控价价值
  • 逻辑回归公式推导-详细版
  • vue3移动端可同时上传照片和视频的组件
  • 项目分析:自然语言处理(语言情感分析)
  • 释放双手,让微信聊天更智能 —— 单机版个人微信智能客服软件介绍
  • Redis学习笔记(三)--Redis客户端
  • SpringBoot技术的车辆管理流程自动化
  • 基于SSM+微信小程序的酒店管理系统1
  • Java项目-基于springboot框架的自习室预订系统项目实战(附源码+文档)
  • 如何高效清除PostgreSQL数据库缓存
  • Flink CDC 报:RPC response exceeds maximum data length
  • 5G智慧医疗的实践先锋:SR830-E工业路由器的理性应用
  • 《PP-OCRv1》论文精读:PaddleOCR是目前SOTA级别的OCR开源技术(截止2024年10月)
  • 【lca,树上差分】P3128 [USACO15DEC] Max Flow P
  • 显示指定目录下的 .c 文件 Linux环境 C语言实现
  • 解释 RESTful API,以及如何使用它构建 web 应用程序。
  • 0 Day漏洞利用激增:谷歌Mandiant警示新安全趋势
  • 【springboot应用-RestTemplate】
  • RHCE--nginx实现多IP访问多网站
  • 形式架构定义语言(ADL)
  • React综合指南(二)
  • Threejs 实现3D 地图(02)创建3d 地图