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;
    }
}
相关推荐
大肘子咒你18 分钟前
数字狂潮来袭
数据结构·c++·1024程序员节
岑梓铭2 小时前
《考研408数据结构》第六章(5.1+5.2+5.3树、二叉树、线索二叉树)复习笔记
数据结构·笔记·考研·408·1024程序员节
苏纪云2 小时前
数据结构<C++>——数组
java·数据结构·c++·数组·动态数组
黄思搏3 小时前
2-3-4树 - 2-3-4 Tree 原理与 C# 实现
数据结构·1024程序员节
潼心1412o3 小时前
数据结构(长期更新)第3讲:顺序表相关操作
数据结构·1024程序员节
共享家95273 小时前
数据结构-并查集
数据结构·c++·算法
小年糕是糕手5 小时前
【C语言】函数栈帧的创建和销毁
java·c语言·开发语言·数据结构·c++·链表
努力努力再努力wz5 小时前
【Linux进阶系列】:信号(下)
java·linux·运维·服务器·开发语言·数据结构·c++
TU^5 小时前
C语言习题~day27
c语言·数据结构·算法
404未精通的狗6 小时前
(数据结构)栈和队列
android·数据结构