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;
    }
}
相关推荐
鱼跃鹰飞6 小时前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
好评1247 小时前
【C++】二叉搜索树(BST):从原理到实现
数据结构·c++·二叉树·二叉搜索树
程序猿炎义7 小时前
【Easy-VectorDB】Faiss数据结构与索引类型
数据结构·算法·faiss
jiaguangqingpanda9 小时前
Day24-20260120
java·开发语言·数据结构
52Hz1189 小时前
力扣24.两两交换链表中的节点、25.K个一组反转链表
算法·leetcode·链表
老鼠只爱大米9 小时前
LeetCode经典算法面试题 #160:相交链表(双指针法、长度差法等多种方法详细解析)
算法·leetcode·链表·双指针·相交链表·长度差法
ValhallaCoder9 小时前
Day53-图论
数据结构·python·算法·图论
C雨后彩虹9 小时前
羊、狼、农夫过河
java·数据结构·算法·华为·面试
Elastic 中国社区官方博客10 小时前
使用瑞士风格哈希表实现更快的 ES|QL 统计
大数据·数据结构·sql·elasticsearch·搜索引擎·全文检索·散列表
重生之后端学习10 小时前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展