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

反转链表的Java实现

1. 题目

反转链表,例如,原链表1-2-3-4-5,反转后为5-4-3-2-1。

2. 迭代法实现

private ListNode reverseList(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    ListNode cur = head.next;
    head.next = null;
    while(cur != null){
        ListNode next = cur.next;
        cur.next = head;
        head = cur;
        cur = next;
    }
    return head;
}

3. 头插法实现

private static ListNode reverseList(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    ListNode newHead = new ListNode(0);
    while(head != null){
        ListNode next = head.next;
        head.next = newHead.next;
        newHead.next = head;
        head = next;
    }
    return newHead.next;
}

http://www.kler.cn/a/153036.html

相关文章:

  • Elasticsearch(ES)概述
  • 【python学习】Python 线程编程(类内多线程编程)
  • 分治算法——75. 颜色分类
  • Leetcode 2948. Make Lexicographically Smallest Array by Swapping Elements
  • 一文带你了解网络安全简史
  • chrome vue devTools安装
  • 【Android知识笔记】架构专题(三)
  • OpenVINO异步Stable Diffusion推理优化方案
  • 中国平安蝉联MSCI-ESG评级“A“级 保持“综合保险及经纪”类别亚太区第一位
  • 【历史资料】北京交通通信原理复试题汇总
  • 血的教训------入侵redis之利用python来破解redis密码
  • Angular 中如何返回上一页?
  • 2023年12月02日新闻简报(国内国际)
  • Django:通过user-agent判断请求是来自移动端还是PC端(电脑端)
  • TCP 重传、滑动窗口、流量控制、拥塞控制的剖析
  • 在线陪诊系统: 医学科技的革新之路
  • Abaqus许可证无效问题
  • 聊聊logback的addtivity属性
  • 【数电笔记】基本和复合逻辑运算
  • 麒麟操作系统光盘救援模式