The title
Leetcode-cn.com/problems/re… Given the head node of a single linked list, reverse the list and return the reversed list.
Train of thought
This problem is relatively simple and clear, double pointer, fast and slow pointer implementation.
The slow pointer points to NULL, the fast pointer points to the head, the fast pointer next points to slow, and then we go together,
code
public ListNode reverseList(ListNode head) {
ListNode fast = head,slow =null;
while(fast != null){
ListNode temp = fast.next;
fast.next = slow;
slow = fast;
fast = temp;
}
return slow;
}
}
Copy the code
You can also use recursion, and recursion is hard to think about, but double Pointers are straightforward. The fourth line of code reverses the list after head, and then reverses it so that next points to the head and next points to null
Public ListNode reverseList (ListNode head) {/ / boundary conditions of the if (head = = null | | head. The next = = null) {return head; } / / 1) pass, since the former backward, first to the last a node list, remember to ret / / 2), after the forward, make the next point to the current of the next node, the next point to null, ReverseList (head. Next); reverseList(head. Next); head.next.next=head; head.next=null; // ListNode(head.next); return ret; }}Copy the code