206--Reverse A Singly Linked List

LinedList Package; 

public class ReverseASinglyLinkedList {
// Solution a: iteration.
ListNode reverseList public (ListNode head) {
ListNode Previous = null;
ListNode Current = head;
the while (Current = null!) {
ListNode Next = current.next;
current.next = Previous;
Previous = Current;
Current = Next;
}
return Current ;
}
/ **
* Method II: recursive
* recursive and iterative actually thinking the same, is to deal with two nodes, so that the pointer between them reversed.
* But, iterative process from start to finish in turn, requires an additional pointer to the next node.
* Is recursively from the tail to the head, back when there will be a current node, so no additional pointer.
* Also note that: p head node is the entire list of the reversed after it was first found, there is no any treatment.
* Rather than each time the nodes to process (reversal) of.
* /
Public ListNode reverseList2 (ListNode head) {
IF (head == null || head.next == null)
return head;
ListNode P = reverseList2 (head.next);
head.next.next = head;
head.next = null;
return P;
}
}

Guess you like

Origin www.cnblogs.com/zhangyuhao/p/11356820.html