算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
wuqingshun3141593 小时前
蓝桥杯 冶炼金属
算法·职场和发展·蓝桥杯
豪斯有话说4 小时前
C++_哈希表
数据结构·c++·散列表
jndingxin4 小时前
OpenCV CUDA模块光流计算-----实现Farneback光流算法的类cv::cuda::FarnebackOpticalFlow
人工智能·opencv·算法
编程绿豆侠4 小时前
力扣HOT100之栈:394. 字符串解码
java·算法·leetcode
朝朝又沐沐5 小时前
基于算法竞赛的c++编程(18)string类细节问题
开发语言·c++·算法
记得早睡~5 小时前
leetcode73-矩阵置零
数据结构·leetcode·矩阵
爱coding的橙子5 小时前
每日算法刷题Day27 6.9:leetcode二分答案2道题,用时1h20min
算法·leetcode·职场和发展
GalaxyPokemon5 小时前
LeetCode - 3. 无重复字符的最长子串
算法·哈希算法·散列表
a.3026 小时前
C++ 时间处理指南:深入剖析<ctime>库
数据结构·c++·算法