返回轨道
算法 · 2026-05-14 · 44 阅读

P9 反转单链表

算法 44 阅读

信号摘要

难度:Easy · 时长:03:23 · leetcode 206 · lintcode 35

P9 反转单链表

未对外公开播放权限
点击查看说明

描述

这个题目说的是,给你一个单链表,你需要反转它,然后返回。

比如说给你的单链表是:

1 -> 2 -> 3 -> 4 -> 5 -> null

你要返回的反转后的链表是:

5 -> 4 -> 3 -> 2 -> 1 -> null

代码

public class AlgoCasts {

  public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
      val = x;
    }
  }

  // Time: O(n), Space: O(1)
  public ListNode reverseList(ListNode head) {
    ListNode cur = head, pre = null;
    while (cur != null) {
      ListNode next = cur.next;
      cur.next = pre;
      pre = cur;
      cur = next;
    }
    return pre;
  }

}

📡 通讯频道