Method One: iterative
The method defines the head node and tail node two variables, by nextTemp record pointer, the pointer sequence 1-> 2-> 3, a second step of modifying reference <-2 <-3 iteratively.
. 1 public ListNode reverseList (ListNode head) { 2 // tail node . 3 ListNode PREV = null ; . 4 // head node . 5 ListNode Curr = head; . 6 the while (! Curr = null ) { . 7 // record the tail current node 8 nextTemp = ListNode curr.next; . 9 // modify the current node is tail node null, (l-> null, 2-> l-> null, 3-> 2-> l-> null) 10 curr.next = PREV; 11 // record the next node in the end node 12 is PREV = Curr; 13 is //The next section nod recording node (original node is tail node) 14 Curr = nextTemp; 15 } 16 return PREV; . 17 }
Complexity Analysis
-
Time complexity: O (n-) . Suppose n- n-is the length of the list, the time complexity is O (n-) .
-
Complexity Space: O (. 1) .