您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页Leetcode 206 Reverse Linked List

Leetcode 206 Reverse Linked List

来源:化拓教育网

题目

Reverse a singly linked list.
单链表反转

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

1.迭代法:

public ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        while(head != null) {
              ListNode next = head.next;
              head.next = newHead;
              newHead = head;
              head = next;
        }
        return newHead;
}
reverseList.png

时间复杂度O(n)

2.递归法

private ListNode reverseList2(ListNode head) {
        if (head == null) {
            return null;
        }
        return reverseList(head, null);
    }

    private ListNode reverseList(ListNode head, ListNode newHead) {
        if (head == null && newHead != null) {
            return newHead;
        }
        ListNode next = head.next;
        head.next = newHead;
        return reverseList(next, head);
    }

时间复杂度: O(n)

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务