博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
反转单链表
阅读量:4091 次
发布时间:2019-05-25

本文共 985 字,大约阅读时间需要 3 分钟。

 

一、问题描述

输入一个链表,反转链表后,输出新链表的表头。

 

二、代码实现

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {        //迭代    public ListNode ReverseList(ListNode head) {        if (head == null || head.next == null) {            return head;        }                ListNode newHead = null;                while (head != null) {            //从原链表中删除头部一个元素cur            ListNode cur = head;    //cur.next = null;  这里无需这么做,在别处最好加上避免出现环            head = head.next;            //将删除的元素cur添加到新链表中(采用头插法)            cur.next = newHead;            newHead = cur;        }                return newHead;    }            //递归    public ListNode ReverseList1(ListNode head) {        if (head == null || head.next == null) {            return head;        }                ListNode next = head.next;        head.next = null;        ListNode newHead = ReverseList(next);        next.next = head;        return newHead;    }    }

 

转载地址:http://jfnii.baihongyu.com/

你可能感兴趣的文章
【git 版本控制】git 提交文件名为中文的文件时,显示数字的问题
查看>>
【小工具】提升开发效率:sourceTree for Mac 可视化 git 工具
查看>>
VS CODE 实用快捷键
查看>>
JS 垃圾回收机制解析
查看>>
js 引用类型 之 数组(Array)及常用方法汇总
查看>>
【前端面试的坑】HTML行内置换元素与非置换元素的区分
查看>>
【前端面试的坑】浏览器的渲染模式
查看>>
JS中如何判断一个数字是整数还是小数
查看>>
【JS 函数】递归函数 之 arguments.callee
查看>>
【JS 函数】JS闭包深入了解
查看>>
【react常见问题】Useless constructor no-useless-constructor报错
查看>>
JS中 target和currentTarget的区别
查看>>
安卓移动端固定在底部的按钮被软件盘顶上去的解决方案
查看>>
一篇文章搞懂前置机到底是什么
查看>>
深入理解埋点
查看>>
JS 纯函数及其应用
查看>>
webpack 快速入门教程
查看>>
【vue 实战】 登录/退出实现原理
查看>>
axios 拦截器的用法
查看>>
浏览器跨域常用解决方案总结
查看>>