【LeetCode】206. Reverse Linked List

Difficulty:easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/reverse-linked-list/java

Reverse a singly linked list.post

Example:ui

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

Follow up:url

A linked list can be reversed either iteratively or recursively. Could you implement both?spa

Intuition

refer to  反轉鏈表 code

pay attention : head.next=nullhtm

Solution

    //iteratively
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    //recursively
    public ListNode reverseList1(ListNode head) {
        if(head == null || head.next==null)
            return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

  

  

Complexity

recursively:blog

Time complexity : O(n)
ip

Space complexity : O(n)

iteratively:

Time complexity : O(n)

Space complexity : O(1)

 

What I've learned

1. When it comes to the Linked List, we should make the best of pointer.

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索