剑指 Offer Java版

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

2019-07-17  本文已影响1164人  孙强Jimmy

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

练习地址

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

方法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;
    }
}

复杂度分析

方法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;
        }
        return reverse(head);
    }
    
    private ListNode reverse(ListNode node) {
        if (node.next == null) {
            return node;
        }
        ListNode head = reverse(node.next);
        node.next.next = node;
        node.next = null;
        return head;
    }
}

复杂度分析

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

上一篇下一篇

猜你喜欢

热点阅读