Difficulty:easy

 More:【目录】LeetCode Java实现

Description

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

Reverse a singly linked list.

Example:

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

Follow up:

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

Intuition

refer to  反转链表 

pay attention : head.next=null

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:

Time complexity : O(n)

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实现

 

相关文章:

  • 2021-09-03
  • 2021-08-30
  • 2022-02-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2020-02-14
  • 2019-09-17
  • 2021-08-20
  • 2021-12-16
  • 2021-06-13
  • 2021-12-06
  • 2021-12-15
相关资源
相似解决方案