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;
    }
}
相关推荐
Fanxt_Ja9 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后12310 小时前
【数据结构】二叉树的概念
数据结构·二叉树
散1121 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19431 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww1 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚1 天前
[数据结构] 排序
数据结构
_不会dp不改名_1 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
睡不醒的kun1 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌1 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long1 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构