[leetcode]206. Reverse Linked List

2023-05-16

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution:

非递归和递归实现。

非递归版本:定义三个指针,pre,cur,next。从前向后修改指针。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null ||head.next == null) {
            return head;
        }
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        ListNode newhead = null;
        while(cur != null) {
            next = cur.next;
            if(next == null) {    //说明到达最后
                newhead = cur;
                cur.next = pre;  //最后一个也要连上前面
                break;
            }
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return newhead;
    }
}

递归版本:和迭代版本思路类似,只不过这个是从后向前修改。

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

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[leetcode]206. Reverse Linked List 的相关文章

  • 如何在 Haskell 中获得列表的中间位置?

    我刚刚开始使用 Haskel 学习函数式编程 我正在慢慢度过Erik Meijer 在 Channel 9 的讲座 http channel9 msdn com shows Going Deep Lecture Series Erik Me
  • 如何访问对列表中对的每个元素?

    我有一个名为 对 的列表 pairs a 1 b 2 c 3 我可以通过以下方式访问元素 for x in pairs print x 其输出如下 a 1 b 2 c 3 但我想访问每对中的每个元素 就像在 c 中一样 如果我们使用pair
  • 根据多个值过滤字典列表

    我有一个字典列表 我想根据多个条件进行过滤 该列表的简化版本如下所示 orders name v price 123 location Mars name x price 223 location Mars name x price 124
  • 在 Django 中为多个查询编写视图的最佳方法?

    这是一个简单的问题 我已经组织了我的模型 以便提供给页面的大多数对象都属于一种类型 项目 该模型包含各种属性 可以帮助我以不同的方式提供服务 我有文章和视频 它们由模型上的 类型 字段确定 类型 文章 等 我有一个列表视图 它显示项目模型中
  • List.Clear() 在 C# 中是如何实现的?

    我假设它使用数组来实现 List 怎么List Clear 实施的 它实际上清理了数组还是只是为此列表创建了一个新数组 public class List private Array array public void Clear1 arr
  • 通过 id 从通用列表中删除对象

    我有一个像这样的域类 public class DomainClass public virtual string name get set public virtual IList
  • 如何加快列表理解速度

    以下是我的清单 col red yellow blue red green yellow pink orange brown pink brown 我的目标是消除每个列表中出现一次的项目 这是我的代码 eliminate w for w i
  • Java 阻止列表实现

    我在 SO 和 Google 上搜索了这个问题的答案 但到目前为止找不到合适的解决方案 我目前正在研究图形路由问题中的 LayerManager 管理器负责提供和重置一组固定的层 我想使用阻止列表来实现消费者 生产者模式 以便只要没有可用的
  • 列表到优先队列

    我有一个 C 大学编程项目 分为两个部分 在开始第二部分时应该使用priority queues hash tables and BST s 我 至少 在优先级队列方面遇到了麻烦 因为它迫使我自己重做第一部分中已经实现的许多代码 该项目是关
  • 如何使用 jQuery 在第二次单击时反转 CSS 动画

    我制作了以下菜单图标 CSS 动画 当我点击它时会触发它 当我使用 jQuery 第二次单击它时 我想使其反向动画 path1 stroke dasharray 33px stroke dashoffset 33px animation l
  • Python:两个列表之间的成对比较:列表 a >= 列表 b?

    如果我想检查列表中的所有元素 a 1 2 3 6 大于或等于另一个列表中对应的元素 b 0 2 3 5 如果 a i gt b i 对于所有i的 则返回 true 否则返回 false 这有逻辑功能吗 比如a gt b 谢谢 你可以这样做
  • Python-使用元组作为列表索引[重复]

    这个问题在这里已经有答案了 我有一个元组列表 tuples list 1 0 2 3 3 2 2 0 我想访问二维数组的元素a例如 使用其中一些元组 for i in range 3 print a tuples list i 应该输出的值
  • Python 3 中的递归搜索 JSON/DICT

    我在 Python 3 中实现了一些 API 这些 API 允许我根据班级代码接收有关学校的信息 但我想知道如何通过类代码获取信息 例子 我输入代码GF528S我希望程序告诉我班级 3C INF 地址 Address 1 Milan 如果可
  • 如何使用 tweepy 仅提取主题标签中的文本?

    我想为我的情感分析项目提取主题标签 但是我得到了一个字典列表 其中包含所有主题标签及其在推文中的索引 我只想要文字 我的代码 data tweepy Cursor api search q since a i until b i items
  • 如何将列表转换为元组列表?

    我想转换 z z a z z a a z to z 2 a 1 z 2 a 2 z 1 我该怎么做 所以 我需要累积以前的值 它的计数器和元组列表 我已创建记录 record acc previous counter tuples 重新定义
  • 如何在 Java 中获得列表的反向列表视图?

    我想在列表上有一个反向列表视图 与List sublist提供列表上的子列表视图 是否有一些函数可以提供此功能 我不想复制该列表 也不想修改该列表 在这种情况下 如果我能在列表上至少获得一个反向迭代器就足够了 另外 我知道如何自己实现这一点
  • 如何从Python列表中的字符串中删除双引号?

    我正在尝试在字典列表中获取一些数据 数据来自 csv 文件 因此都是字符串 文件中的键都有双引号 但由于这些都是字符串 我想删除它们 这样它们在字典中看起来像这样 key value 而不是这个 key value 我尝试简单地使用 str
  • Django查询:如何过滤对象以排除列表中的id?

    如何在查询中进行过滤 以便结果排除 ID 属于列表的任何对象实例 可以说我有 object id list 1 5 345 MyObject objects filter Q time gte datetime now Q what to
  • 如何在 Haskell 中制作打勾游戏的图案?

    实现有 2 个参数的函数 ticktick 第一个参数是自然数元组 定义游戏场地的行数和列数 第二个列表包含由玩家 x 和玩家 o 轮流玩的坐标给出的井字游戏比赛的记录 打印游戏的实际状态 其中游戏区域将由字符 和 界定 空方块 以及字符
  • Collections.sort(list) 和 list.sort(Comparator) 之间的区别

    有什么理由让我应该选择Collections sort list 方法而不是简单地调用list sort 内部Collections sort只是调用sort的方法List无论如何 上课 令人惊讶的是几乎每个人都告诉我使用Collectio

随机推荐

  • 设计模式之适配器模式

    适配器模式是作为两个不兼容的接口之间的桥梁 这种类型的设计模式属于结构型模式 xff0c 它结合了两个独立接口的功能 这种模式涉及到一个单一的类 xff0c 该类负责加入独立的或不兼容的接口功能 举个真实的例子 xff0c 读卡器是作为内存
  • 设计模式之单例模式

    1 懒汉式 xff0c 线程不安全 public class Demo1 private static Demo1 instance private Demo1 public static Demo1 getInstance if inst
  • Lambda表达式详解

    Java 8最值得学习的特性就是Lambda表达式 Lambda写的好可以极大减少代码冗余 xff0c 同时可读性也好过冗长的内部类 xff0c 匿名类 举例说明一下 xff1a xff08 1 xff09 创建线程传统写法 xff1a T
  • Android8.0以上实现APP(应用)开机自启动

    一 程序中实现APP开机自启动 可参考 xff1a https www cnblogs com jetereting p 4572302 html 二 设置APP开机自启动权限 小米手机设置开机启动应用权限 xff08 Android9 0
  • 跳台阶问题

    1 输出斐波那契数列的第n项 直接上代码 xff1a public class Fibonacci public static int fibonacci int n if n 61 61 0 return 0 if n 61 61 1 r
  • 字符串编辑距离

    字符串的编辑距离 xff0c 又称为Levenshtein距离 是利用字符操作 xff0c 把字符串A转换成字符串B所需要的最少操作数 其中 xff0c 字符操作包括 xff1a 删除一个字符插入一个字符修改一个字符 例如对于 34 hel
  • [leetcode]807.Max Increase to Keep City Skyline

    In a 2 dimensional array grid each value grid i j represents the height of a building located there We are allowed to in
  • [leetcode]1038. Binary Search Tree to Greater Sum Tree

    Given the root of a binary search tree with distinct values modify it so that every node has a new value equal to the su
  • [leetcode]344. Reverse String

    Write a function that reverses a string The input string is given as an array of characters char Do not allocate extra s
  • [leetcode]136. Single Number

    Given a non empty array of integers every element appears twice except for one Find that single one Note Your algorithm
  • [leetcode]412. Fizz Buzz

    Write a program that outputs the string representation of numbers from 1 to n But for multiples of three it should outpu
  • [leetcode]94. Binary Tree Inorder Traversal

    Given a binary tree return the inorder traversal of its nodes 39 values Example Input 1 null 2 3 1 2 3 Output 1 3 2 Solu
  • [leetcode]46. Permutations

    Given a collection of distinct integers return all possible permutations Example Input 1 2 3 Output 1 2 3 1 3 2 2 1 3 2
  • [ERROR][idea报错]Unmapped Spring configuration files found.

    idea启动Event Log提示 xff1a Spring Configuration Check Unmapped Spring configuration files found Please configure Spring fac
  • (备忘)android模拟器摄像头模拟

    Camera分Front Camera和Back Camera 通常我们模拟后摄像头就可以了 三个选项 none 表示没有摄像头 打开摄像应用会崩溃 emulated 系统模拟一个动态的画面 在黑白格背景上随机移动的矩形色块 Webcam
  • [leetcode]22. Generate Parentheses

    Given n pairs of parentheses write a function to generate all combinations of well formed parentheses For example given
  • [leetcode]238. Product of Array Except Self

    Given an array nums of n integers where n gt 1 return an array output such that output i is equal to the product of all
  • [ERROR]ubuntu18.04安装Postman报错

    解压完成以后 xff0c 进入解压目录 xff0c 执行 Postman xff0c 提示 xff1a Postman error while loading shared libraries libgconf 2 so 4 cannot
  • [leetcode]347. Top K Frequent Elements

    Given a non empty array of integers return the k most frequent elements Example 1 Input nums 61 1 1 1 2 2 3 k 61 2 Outpu
  • [leetcode]206. Reverse Linked List

    Reverse a singly linked list Example Input 1 gt 2 gt 3 gt 4 gt 5 gt NULL Output 5 gt 4 gt 3 gt 2 gt 1 gt NULL Follow up