算法题 — 链表反转

将单链表的链接顺序反转过来

  • 例:输入:1->2->3->4->5
  • 输出:5->4->3->2->1

使用两种方式解题

1 迭代

java 复制代码
static class ListNode {
    int val;
    ListNode next;

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public static ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode pre = null, cur = head, next;
    while (cur != null) {
        // 保存下一个节点
        next = cur.next;
        // 反转链表
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

public static void main(String[] args) {
   ListNode node5 = new ListNode(5, null);
   ListNode node4 = new ListNode(4, node5);
   ListNode node3 = new ListNode(3, node4);
   ListNode node2 = new ListNode(2, node3);
   ListNode node1 = new ListNode(1, node2);
   reverseList(node1)
}

2 递归

java 复制代码
public static ListNode recursion(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode newHead = recursion(head.next);
    head.next.next = head;
    head.next = null;

    return newHead;
}
相关推荐
NAGNIP16 分钟前
一文搞懂CNN经典架构-AlexNet!
人工智能·算法
2401_8785302142 分钟前
自定义内存布局控制
开发语言·c++·算法
专注VB编程开发20年42 分钟前
PNG、GIF透明游戏角色人物输出一张图片技巧,宽度高度读取
算法
CoderCodingNo1 小时前
【CSP】CSP-J 2025真题 | 异或和 luogu-P14359 (相当于GESP六级水平)
算法
keep intensify1 小时前
打家劫舍3
算法·深度优先
历程里程碑1 小时前
Protobuf 环境搭建:Windows 与 Linux 系统安装教程
linux·运维·数据结构·windows·线性代数·算法·矩阵
keep intensify1 小时前
岛屿数量--
算法·深度优先
代码探秘者1 小时前
【算法】吃透18种Java 算法快速读写模板
数据结构·数据库·python·算法·spring
2301_816651221 小时前
C++模块化设计原则
开发语言·c++·算法
gaozhiyong08131 小时前
提示词的解剖学:Gemini 3.1 Pro 提示工程高级策略与国内实战
人工智能·算法·机器学习