算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
C++ 老炮儿的技术栈1 分钟前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java37 分钟前
R-tree详解
java·算法·r-tree
MarkHard1231 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
王RuaRua1 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表
一只鱼^_2 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼2 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程2 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
寒小松2 小时前
Problem E: List练习
java·数据结构·list
↣life♚3 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割
zqh176736464693 小时前
2025年阿里云ACP人工智能高级工程师认证模拟试题(附答案解析)
人工智能·算法·阿里云·人工智能工程师·阿里云acp·阿里云认证·acp人工智能