The question

Define a function that takes the head node of a linked list, reverses the list, and outputs the head node of the reversed list.

The sample

Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULLCopy the code

answer

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
    public ListNode reverseList(ListNode head) {
        // Define three linked lists for swap and temporary storage
	// Correspond to the front/current/back positions respectively
	ListNode pre = null;
        ListNode current = head;
        ListNode next = null;
	
	// When the current pointer is not null
        while(current ! =null) {// if the current node is A->B
            next = current.next;
	    // Swap the values of the before and after Pointers
	    // current -> next, temporary pre = null
	    Next -> current -> pre(null)
            current.next = pre;
            pre = current;
	    // Continue to swap the next pointer
            current = next;
        }
        returnpre; }}Copy the code