LeetCode 206. 反转链表

206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]

Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]

Output: [2,1]

Example 3:

Input: head = []

Output: []

解题思路:

  1. 递归
  2. 双指针

法一:

class Solution {
    public ListNode reverseList(ListNode head) {
        // Recursion 
        // Time: O(n) 
        // Space: O(n)
        if (head == null || head.next == null) {
            return head;
        }
        ListNode ret = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return ret;
    }
}

 法二:

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

相关推荐

  1. leetcode206.

    2023-12-17 18:24:03       37 阅读
  2. LeetCode206

    2023-12-17 18:24:03       31 阅读
  3. leetcode 206

    2023-12-17 18:24:03       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-17 18:24:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-17 18:24:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-17 18:24:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-17 18:24:03       18 阅读

热门阅读

  1. (python)正则表达式进阶

    2023-12-17 18:24:03       45 阅读
  2. 正则表达式的规则

    2023-12-17 18:24:03       43 阅读
  3. Web应用安全—信息泄露

    2023-12-17 18:24:03       38 阅读
  4. oracle怎么存放json好

    2023-12-17 18:24:03       22 阅读
  5. Python学习笔记第七十三天(OpenCV简介)

    2023-12-17 18:24:03       41 阅读
  6. 【Qt5】QDialog的pos函数

    2023-12-17 18:24:03       35 阅读
  7. MHA实验和架构

    2023-12-17 18:24:03       29 阅读