LeetCode - 206. Reverse Linked List

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?

反转单链表,看到我好几年前通过的代码居然是用List遍历保存之后再倒序遍历反转,然而还RE了好几次。。。往事突然浮现在脑海,没忍住又重写了一下。

耗时0ms

复制代码
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, prev = null, temp = null;
        while (cur != null) {
            temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}
复制代码

以前的代码是这样的(耗时464ms):

复制代码
public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ArrayList<Integer> list = new ArrayList<Integer>();
        ListNode p = head;
        while(p!=null) {
            list.add(p.val);
            p = p.next;
        }
        ListNode q = head;
        for(int i=list.size()-1; i>=0; i--) {
            q.val = list.get(i);
            q = q.next;
        }
        return head;
        
    }
}
复制代码

 

posted @   Pickle  阅读(245)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2015-10-31 SpringMVC架构浅析
2015-10-31 编码问题
2015-10-31 Spring MVC全局异常处理与拦截器校检
点击右上角即可分享
微信分享提示