Java数据结构与算法练习二(韩顺平老师版)

用单链表模拟栈

/**
 * 作业:用单链表模拟栈
 */
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 + '\'' +
                '}';
    }
}

猜你喜欢

转载自blog.csdn.net/zjdzka/article/details/109731715