Wins the Offer (list) - reverse list

  (Reverse list) subject description:


After entering a list inverted list, the new list of the output header.


  Problem-solving ideas: the topic and the list is a singly linked list, so in order to reverse the entire list, we need to point to sort out problems between the nodes, the last node points to the second countdown, the penultimate point to the bottom third a, ......, the second one to the first, the first point to a null; nodes which need to be picked one by one, to make adjustments from the list; this correction requires two auxiliary pointers: pre record its previous node position, so that the next pointer of the node points to the previous node, but before pointing to a knot p after recording a pointer to a node needs to address the point before, to avoid the loss of node .

    • Example head node to the following steps:
    • 1. head inversion point is null, so that the former is not inverted when a node should be null, the pointer is initialized pre null;
    • 2. The recording head of the next node with the pointer p head.next;
    • 3. Remove the head from the list, that is, let head.next pointing pre;
    • 4. The removal of the completed head node and a node connected to the front, then we need to operate at a junction: and so the need to pre head movement, so that pre pointing head, head point to the next node.
    • This operation is repeated until the head has completed four original list, point to null, the end of the cycle, return to pre.
/ * 
Public class ListNode { 
    int Val; 
    ListNode Next = null; 

    ListNode (int Val) { 
        this.val = Val; 
    } 
} * / 
public class Solution { 
    public ListNode ReverseList (ListNode head) { 
        // empty list is determined and the length of the list 1 
        IF (head == null || head.next == null) { 
            return head; 
        } 
        // initialization for storing two pointers before and after the current node position 
        ListNode pre = null; 
        ListNode NX = null; 
        the while (! head = null) { 
            // first storage location of the next node of the current node 
            NX = head.next; 
            // complete reversal (so head.next directed pre) 
            head.next = pre;
            A node pointer movement // 
            pre = head;
            // move the current node, the above first step to save the next node position 
            head = NX; 
        } 
        return pre; 
    } 
}

  

Guess you like

Origin www.cnblogs.com/dashenaichicha/p/12572366.html