Reverse a singly linked list.
Example:
Input: 1-> 2-> 3-> 4- > 5-> NULL Output: 5-> 4-> 3-> 2- > 1-> NULL
Advanced:
You can reverse iterative or recursively list. Can you solve this question in two ways?
solution
Method One: iterative
Assuming that there is a linked list 1 → 2 → 3 → Ø
, we want to change it Ø ← 1 ← 2 ← 3
.
When traversing the list, the current node next
pointer to point to the previous element. Since the node which is not a reference node, which must be stored in advance before the element. Prior to change the reference, the other pointers needed to store the next node. Do not forget to return the new head of reference at the end!
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; }
Complexity Analysis
-
Time complexity: O (n-) O ( n- ). Suppose n- n-is the length of the list, the time complexity is O (n-) O ( n- ).
-
Space complexity: O (. 1) O ( . 1 )