美文网首页安卓开发
Leetcode 206 Reverse Linked List

Leetcode 206 Reverse Linked List

作者: __Saber__ | 来源:发表于2019-06-11 14:46 被阅读0次

题目

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)

相关文章

网友评论

    本文标题:Leetcode 206 Reverse Linked List

    本文链接:https://www.haomeiwen.com/subject/jjwffctx.html