算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
suhan9 分钟前
【数据结构】五、树:7.哈夫曼树、哈夫曼编码
数据结构·算法·排序算法
kkhimself17 分钟前
POJ-3126
算法
suhan27 分钟前
【数据结构】五、树:6.平衡二叉树AVL
数据结构·算法·排序算法
suhan28 分钟前
【数据结构】五、树:5.二叉排序树BST
数据结构·算法·排序算法
爱读书的小胖44 分钟前
80. 删除有序数组中的重复项 II
java·数据结构·算法
臻选云栗子1 小时前
PCDN跑不起来?先别甩锅给平台,问题可能出在这
算法·程序员
小画家~1 小时前
vue3 里面的 itemList.reduce
前端·数据结构·算法
tryxr2 小时前
索引概念和索引底层数据结构
数据结构·索引
All for pursuit.2 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_32 小时前
LeetCode.101.对称二叉树
数据结构·leetcode