After entering a list inverted list, the new list of the output header.
Thinking: need to define three pointers, pointing to the currently traversed node, and its previous node to a node.
Test Case:
List head pointer (1) is a null input
List (2) only one input node
List (3) has a plurality of input nodes
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode newHead = null; ListNode curNode = head, prevNode = null; while(curNode != null){ ListNode nextNode = curNode.next; if(nextNode == null) newHead = curNode; curNode.next = prevNode; prevNode = curNode; curNode = nextNode; } return newHead; } }
Recursive solution for reversing the list:
public ListNode ReverseList (ListNode head) { IF (head == null || head.next == null ) return head; // first inverting behind list, go to the end of the linked list node ListNode pReverseNode = ReverseList (head.next ); // then the current node as a node subsequent nodes behind head.next.next = head; head.next = null ; return pReverseNode; }