Acwing 35. 反转链表

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

思考题:

请同时实现迭代版本和递归版本。

数据范围

链表长度 [0,30]

样例

复制代码
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL

思路

很怪,这个头结点不是指的不存储任何信息的结点,更类似于头指针
代码

javascript 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        //必须这么写,如果写成pre = head, cur = head -> next会陷入死循环
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

递归代码

javascript 复制代码
/**
 * 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 tail = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return tail;
    }
}
相关推荐
躲着人群8 小时前
次短路&&P2865 [USACO06NOV] Roadblocks G题解
c语言·数据结构·c++·算法·dijkstra·次短路
蓝风破云11 小时前
C++实现常见的排序算法
数据结构·c++·算法·排序算法·visual studio
浩浩测试一下12 小时前
06高级语言逻辑结构到汇编语言之逻辑结构转换 for (...; ...; ...)
汇编·数据结构·算法·安全·web安全·网络安全·安全架构
封奚泽优14 小时前
MATLAB入门教程
数据结构·matlab·deepseek
野生的编程萌新15 小时前
【数据结构】从基础到实战:全面解析归并排序与计数排序
数据结构·算法·排序算法
Mercury_Lc15 小时前
【链表 - LeetCode】206. 反转链表【带ACM调试】
算法·链表
whitepure17 小时前
万字详解常用数据结构(Java版)
java·数据结构·后端
2025年一定要上岸18 小时前
【数据结构】-4-顺序表(上)
java·开发语言·数据结构
Vect__1 天前
链表漫游指南:C++ 指针操作的艺术与实践
数据结构·c++·链表
古译汉书1 天前
蓝桥杯算法之基础知识(2)——Python赛道
数据结构·python·算法·蓝桥杯