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;
    }
}
相关推荐
Savior`L2 小时前
二分算法及常见用法
数据结构·c++·算法
甄心爱学习4 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~4 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
有时间要学习5 小时前
面试150——第二周
数据结构·算法·leetcode
freedom_1024_5 小时前
红黑树底层原理拆解
开发语言·数据结构·b树
liu****5 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表
minji...5 小时前
Linux 基础IO(一) (C语言文件接口、系统调用文件调用接口open,write,close、文件fd)
linux·运维·服务器·网络·数据结构·c++
CQ_YM6 小时前
数据结构之栈
数据结构·算法·
xlq223226 小时前
24.map set(下)
数据结构·c++·算法
立志成为大牛的小牛7 小时前
数据结构——五十四、处理冲突的方法——开放定址法(王道408)
数据结构·学习·程序人生·考研·算法