Example:
A linked list is as follows:
public class LinkNode {private int value;private LinkNode nextNode;}
Use recursion to find the node with the largest linked list value. The implementation is as follows:
Package com;/*** recursively obtain the node with the maximum value of a single-chain table ** @ author caozp **/public class linknode {private int value; private linknode nextnode; Public linknode () {} public linknode (INT value) {This. value = value;} public linknode (INT value, linknode nextnode) {This. value = value; this. nextnode = nextnode;} public int getvalue () {return value;} public void setvalue (INT value) {This. value = value;} public linknode getnextnode () {Return nextnode;} public void setnextnode (linknode nextnode) {This. nextnode = nextnode;} @ overridepublic string tostring () {return "linknode [value =" + value + ", nextnode =" + nextnode + "]";} public void printnode () {stringbuilder STR = new stringbuilder ("["); linknode node = getnextnode (); While (node! = NULL) {Str. append (node. getvalue ()). append (","); node = node. getnextnode ();} Str. append ("]"); system. out. println (STR);} public static void main (string [] ARGs) {linknode head = new linknode (123); linknode node = new linknode (156 ); linknode node1 = new linknode (0); linknode node2 = new linknode (456); linknode node3 = new linknode (-100); linknode node4 = new linknode (2); head. setnextnode (node); node. setnextnode (node1); node1.setnextnode (node2); node2.setnextnode (node3); node3.setnextnode (node4); head. printnode (); // linknode maxnode = getmaxnode (head); // system. out. println (maxnode); linknode minnode = getminnode (head); system. out. println (minnode);}/*** obtain the largest node in the chain table ** @ Param head * @ return */public static linknode getmaxnode (linknode head) {If (Head = NULL) {Throw new nullpointerexception ("Arg is null");} // If (head. getnextnode () = NULL) {return head;} // the value of the current node is greater than nextnode. Set nextnodeif (head. getvalue ()> head. getnextnode (). getvalue () {linknode childnextnode = head. getnextnode (). getnextnode (); head. setnextnode (childnextnode); Return getmaxnode (head);} else {// otherwise, compare the nextnodereturn getmaxnode (head. getnextnode () ;}}/*** obtain the largest node in the chain table ** @ Param head * @ return */public static linknode getminnode (linknode head) {If (Head = NULL) {Throw new nullpointerexception ("Arg is null");} // If (head. getnextnode () = NULL) {return head;} // 0 15 56-17 189 // the value of the current node is greater than that of nextnode. Set nextnodeif (head. getvalue ()