Question 24th:
Linked list operations,
Single-linked list in-place inversion
Idea: would like to take two pointers to the current node and the previous node, moving the pointer backwards in the process of the current node's next pointer to the previous node, but this will not continue to move the current node backward ....
Change the idea, for n each node, reverse operation can be decomposed into reverse n-1 nodes, and then put the first node in the reverse order of good n-1 elements can be after the f (n) = [F (n-1), 1] and finally return to the recursion ...
In fact, recursion can also be attributed to the Divide&conquer category?
1 PackageCom.rui.microsoft;2 3 Public classTest24_reverselinklist {4 5 Public Static voidMain (string[] args) {6Node Node1 =NewNode (1);7Node Node2 =NewNode (2);8Node1.next =Node2;9Node Node3 =NewNode (3);TenNode2.next =Node3; OneNode node4 =NewNode (4); ANode3.next =Node4; -Node NODE5 =NewNode (5); -Node4.next =Node5; the -Node last =reverse (node1); -System.out.println ("Last Node:" +last.value); -System.out.print ("New Order:"); + while(NULL!=NODE5) { -System.out.print ("" +node5.value); +NODE5 =Node5.next; A } at } - - Public Staticnode Reverse (node head) { - if(NULL= = head)return NULL; - if(NULL= = Head.next)returnhead; -Node last =reverse (head.next); inLast.next =head; -Head.next =NULL; to returnhead; + } - the Static classnode{ * intvalue; $ Node Next;Panax Notoginseng PublicNode (intvalue) { - This. Value =value; the } + } A}
Microsoft algorithm 100 Questions 24 in-place reverse single linked list