package offer;
import java.util.Stack;
/**
* offer interview 05
*/
public class Test05 {
public static class ListNode{
int val;
ListNode next;
public ListNode(){
}
public ListNode(int val){
this.val = val;
}
}
/**
* method 1
* @param root
*/
public static void printListInverselyUsingIteration(ListNode root){
Stack<ListNode> stack = new Stack<>();
while (root != null){
stack.push(root);
root = root.next;
}
ListNode tmp;
while (!stack.isEmpty()){
tmp = stack.pop();
System.out.print(tmp.val + " ");
}
System.out.println();
}
/**
* method 2
* @param root
*/
public static void printListInverselyUsingRecursion(ListNode root){
if (root != null){
printListInverselyUsingRecursion(root.next);
System.out.print(root.val + " ");
}
}
public static void main(String[] args){
ListNode root = new ListNode(1);
root.next = new ListNode(2);;
root.next.next = new ListNode(3);
root.next.next.next = new ListNode(4);
root.next.next.next.next = new ListNode(5);
printListInverselyUsingIteration(root);
System.out.println("==========");
printListInverselyUsingRecursion(root);
}
}
剑指offer-问题5
猜你喜欢
转载自blog.csdn.net/ma451152002/article/details/83142445
今日推荐
周排行