剑指Offer Java版 面试题24:反转链表

题目:输入一个链表,反转链表后,输出新链表的表头。

练习地址

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

方法1:遍历

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode reversedHead = null, node = head, prev = null;
        while (node != null) {
            ListNode next = node.next;
            if (next == null) {
                reversedHead = node;
            }
            node.next = prev;
            prev = node;
            node = next;
        }
        return reversedHead;
    }
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(1)。

方法2:递归

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode reversedHead = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return reversedHead;
    }
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(n)。

👉剑指Offer Java版目录
👉剑指Offer Java版专题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容