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 + '\'' +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值