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;
    }
}
相关推荐
m0_672703311 小时前
上机练习第51天
数据结构·c++·算法
仰泳的熊猫2 小时前
题目2577:蓝桥杯2020年第十一届省赛真题-走方格
数据结构·c++·算法·蓝桥杯
灰色小旋风2 小时前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
ccLianLian4 小时前
数论·欧拉函数
数据结构·算法
会编程的土豆4 小时前
C++中的 lower_bound 和 upper_bound:一篇讲清楚
java·数据结构·算法
HUTAC5 小时前
关于进制转换及其应用的算法题总结
数据结构·c++·算法
小刘不想改BUG5 小时前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
XW01059995 小时前
6-函数-1 使用函数求特殊a串数列和
数据结构·python·算法
沉鱼.445 小时前
枚举问题集
java·数据结构·算法
罗超驿5 小时前
Java数据结构_栈_算法题
java·数据结构·