More:【目錄】LeetCode Java實現html
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
refer to 反轉鏈表 code
pay attention : head.next=nullhtm
//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; }
recursively:blog
Time complexity : O(n)
ip
Space complexity : O(n)
iteratively:
Time complexity : O(n)
Space complexity : O(1)
1. When it comes to the Linked List, we should make the best of pointer.
More:【目錄】LeetCode Java實現