// 逆序打印
public void reversePrint(Person headNode){
if(headNode.next == null){
return;// 空列表,不可以打印
}
Stack<Person> person = new Stack<>();
// 压栈
Person cur = headNode.next;
while( cur != null){
person.push(cur);
cur = cur.next;
}
// 打印
while(person.size() > 0){
System.out.println(person.pop());
}
}
public class Person {
public int id;
public String name;
public Person next;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
测试类:
public static void main(String[] args) {
Person person1 = new Person(1,"zs");
Person person2 = new Person(2,"ls");
Person person3 = new Person(3,"ww");
SingleLinkedList single = new SingleLinkedList();
single.add(person1);
single.add(person2);
single.add(person3);
System.out.println("显示列表");
single.show(single.getHead());
System.out.println("逆序打印。。。");
single.reversePrint(single.getHead());
}