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;
    }
}
相关推荐
mmmmath_32 小时前
LeetCode.104.二叉树的最大深度
数据结构·leetcode
信奥卷王9 小时前
[GESP202509 六级] 划分字符串(含视频)
数据结构·算法
m0_752035639 小时前
Redis 数据结构总结
数据结构·数据库·redis
tachibana29 小时前
Go 语言的 Map 是否是并发安全的?
开发语言·数据结构·后端·golang·go·语言
Logic10110 小时前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
我命由我1234510 小时前
LRU 缓存淘汰策略
数据结构·redis·学习·mysql·算法·缓存·学习方法
垆边人似月.11 小时前
华为题:合并区间
数据结构·c++·算法
垆边人似月.11 小时前
华为题:滑动窗口最大值
数据结构·c++·算法
m0_5474866611 小时前
《数据结构 (C语言)》期末试卷及答案(10套)2026版
c语言·开发语言·数据结构
杜 硕12 小时前
归并排序详解
数据结构·算法·排序算法