算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
I_LPL6 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱6 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073217 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824968 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you9 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018729 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563249 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920749 小时前
C++代码国际化支持
开发语言·c++·算法
m0_6727033110 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ10 小时前
【day60】
算法·深度优先·图论