【LeetCode】206. Reverse Linked List
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实现