题目:输入一个链表的头结点,从尾到头反过来打印出每个节点
分析:利用栈即可解决
import java.util.Stack;
public class ReverseLinkedList {
public static void main(String[] args) {
Node[] nodes = new Node[10];
for(int i=0;i<10;i++){
nodes[i] = new Node(i);
}
for(int i=0;i<9;i++){
nodes[i].setNext(nodes[i+1]);
}
print(nodes[0]);
}
public static void print(Node root){
Stack
stack = new Stack<>();
while(root!=null){
stack.push(root);
root = root.getNext();
}
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
class Node{
private int data;
private Node next;
public Node(int data) {
super();
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return "Node [data=" + data + "]";
}
public Node() {
super();
}
}