Use stack, reverse can be solved by stack
??
Press the data one by one into the stack first
??
And then another one pops up
??
Another way is to use recursion, recursion is actually similar to the stack
??
Method One:
??
Package printListReversed5;
??
Import Java.util.Stack;
??
public class PrintListReversed5 {
static void Printlistreversed (ListNode head) {
if (head! = null) {
stack<listnode> stack = new stack<> ();
while (head! = null) {
Stack.push (head);
head = Head.nextnode;
}
while (!stack.isempty ()) {
System.out.println (Stack.pop (). data);
}
}
}
??
public static void Main (string[] args) {
TODO auto-generated Method Stub
ListNode Headnode = new ListNode ();
Headnode.data = 1;
Headnode.nextnode = null;
ListNode L1 = new ListNode ();
L1.data = 2;
ListNode L2 = new ListNode ();
L2.data = 3;
Headnode.nextnode = L1;
L1.nextnode = L2;
L2.nextnode = null;
Printlistreversed (Headnode);
}
??
}
??
Class ListNode {
int data;
ListNode NextNode;
}
??
Method Two:
??
private static void printlistreversed (ListNode headnode) {
if (headnode.nextnode!=null) {
Printlistreversed (Headnode.nextnode);
}
System.out.println (Headnode.data);
}
? ?
Print the list from tail to head 5