算法题 — 链表反转

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

  • 例:输入: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;
}
相关推荐
baizhigangqw15 分钟前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶
算法·启发式算法·web app
C雨后彩虹28 分钟前
最多等和不相交连续子序列
java·数据结构·算法·华为·面试
cpp_25011 小时前
P2347 [NOIP 1996 提高组] 砝码称重
数据结构·c++·算法·题解·洛谷·noip·背包dp
Hugh-Yu-1301231 小时前
二元一次方程组求解器c++代码
开发语言·c++·算法
编程大师哥2 小时前
C++类和对象
开发语言·c++·算法
今天又在写代码2 小时前
数据结构v2
数据结构
加农炮手Jinx2 小时前
LeetCode 146. LRU Cache 题解
算法·leetcode·力扣
Rabitebla2 小时前
C++ 和 C 语言实现 Stack 对比
c语言·数据结构·c++·算法·排序算法
加农炮手Jinx2 小时前
LeetCode 128. Longest Consecutive Sequence 题解
算法·leetcode·力扣
旖-旎2 小时前
递归(汉诺塔问题)(1)
c++·学习·算法·leetcode·深度优先·递归