package yyds;
import java.util.Stack;
public class zhan {
public static void main(String args[]) {
Hero hero1=new Hero(1,"a","A");
Hero hero2=new Hero(2,"b","B");
Hero hero3=new Hero(3,"v","v");
Lian l=new Lian();
l.add(hero1);
l.add(hero2);
l.add(hero3);
l.show();
System.out.println();
l.reversePrint(l.getHead());
}
}
class Lian{
Hero head=new Hero(0,"","");
public void add(Hero hero) {
Hero temp=head.next;
if(temp==null) {
return ;
}
while(true) {
if(temp.next==null) {
break;
}temp=temp.next;
}
temp.next=hero;
}
public void show() {
Hero temp=head.next;
if(temp==null) {
System.out.println("空");
}
while(true) {
if(temp.next==null) {
break;
}temp=temp.next;
System.out.println(temp);
}
}
public Hero getHead() {
return head;
}
public void reversePrint(Hero head) {
if(head.next==null) {
return ;
}
Stack <Hero> stack=new Stack<Hero>(); //栈
Hero cur=head.next;
while(cur!=null) {
stack.push(cur); //将各节点压入栈中
cur=cur.next;
}
System.out.println(stack.pop()); //输出栈
}
}
class Hero {
int no;
String name;
String nickname;
Hero next;
Hero(int no,String name,String nickname){
this.no=no;
this.name=name;
this.nickname=nickname;
}
public String toString() {
return "Hero [no=" + no + ", name=" + name + ", nickname=" + nickname + "]";
}
}
结果
Hero [no=1, name=a, nickname=A]
Hero [no=2, name=b, nickname=B]
Hero [no=3, name=v, nickname=v]
Hero [no=3, name=v, nickname=v]
Hero [no=2, name=b, nickname=B]
Hero [no=1, name=a, nickname=A]