用单链表模拟栈
public class SingleLinkedListStackWork {
public static void main(String[] args) {
Student student = new Student(1,"tom");
Student student2 = new Student(5,"title");
Student student3 = new Student(3,"zjd");
SingleLinkedListStack singleLinkedListStack = new SingleLinkedListStack();
singleLinkedListStack.add(student);
singleLinkedListStack.add(student2);
singleLinkedListStack.add(student3);
System.out.println("入栈:");
singleLinkedListStack.show();
System.out.println("出栈:");
ReversePrint(singleLinkedListStack.getHead());
}
public static void ReversePrint(Student head){
if(head.next==null){
return;
}
Stack<Student> stack = new Stack<Student>();
Student temp = head.next;
while (temp!=null){
stack.push(temp);
temp=temp.next;
}
while (stack.size()>0){
System.out.println(stack.pop());
}
}
}
class SingleLinkedListStack{
private Student head = new Student(0,"");
public Student getHead(){
return head;
}
public void add(Student student){
Student temp = head;
while (true){
if(temp.next==null){
break;
}
temp=temp.next;
}
temp.next=student;
}
public void show(){
if(head.next==null){
System.out.println("链表为空");
return;
}
Student temp = head.next;
while (true){
if(temp==null){
break;
}
System.out.println(temp);
temp=temp.next;
}
}
}
class Student{
public int no;
public String name;
public Student next;
public Student(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}