算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
_w_z_j_5 分钟前
最小栈(栈)
数据结构
fufu031125 分钟前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
Yingye Zhu(HPXXZYY)44 分钟前
Solution to Luogu P6340
算法
小熳芋1 小时前
单词搜索- python-dfs&剪枝
算法·深度优先·剪枝
Xの哲學1 小时前
Linux SLAB分配器深度解剖
linux·服务器·网络·算法·边缘计算
bu_shuo1 小时前
MATLAB中的转置操作及其必要性
开发语言·算法·matlab
高洁012 小时前
图神经网络初探(2)
人工智能·深度学习·算法·机器学习·transformer
爱装代码的小瓶子2 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
思成Codes2 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法
虾..3 小时前
Linux 简单日志程序
linux·运维·算法