import java.util.Stack;
//要定义一个节节点类
class Node{
int data;
Node next = null;
public Node(int data)
{
this.data=data;
}
}
public class Interview6 {
/**
* 题目:从尾到头打印链表
* 输入一个链表的头节点,从尾到头打印出每个节点的值
* 思路1:用栈的方式
* 思路2:递归
*/
//要定义一个节节点类
public static void main(String[] args){
Interview6 i = new Interview6();
Node node0 = new Node(0);
Node node1=new Node(1);
Node node2=new Node(2);
node0.next=node1;
node1.next=node2;
//用栈的方式
i.printLinkbstack(node0);
//用递归的方式
i.pringLinkbyRecursion(node0);
}
//方法一用栈的方式
public void printLinkbstack(Node linkhead){
Stack<Node> stack =new Stack<Node>();
Node tmp=linkhead;
while(tmp!=null){
stack.push(tmp);
tmp=tmp.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop().data);
}
}
//递归
public void pringLinkbyRecursion(Node linkhead){
if(linkhead!=null){
if(linkhead.next!=null){
pringLinkbyRecursion(linkhead.next);
}
System.out.println(linkhead.data);
}
}
}