java使用单链表模拟栈

思路:(压栈时候采用头插法)

 代码演示:

public class LinkedListStack {
    private Person top = new Person(-1);
    // 判断栈是否为空
    public boolean isEmpty(){
        return top.getNo() == -1;
    }


    // 入栈
    public void push(Person person){
       Person temp = top;
        if(top.getNext() == null){// 第一个节点的插入
            top.setNext(person);
            return;
        }
        Person cur = top.getNext();
        top.setNext(person);
        person.setNext(cur);
    }

    // 出栈
    public void pop(){
        System.out.println("节点为:"+top.getNext().getNo());
        top = top.getNext();
    }

    // 遍历
    public void show(){
        if(top.getNext() == null){
            System.out.println("栈空。。。");
            return;
        }
        Person temp = top;
        while(temp.getNext() != null){
            System.out.println("节点为:"+temp.getNext().getNo());
            temp = temp.getNext();
        }
    }
}

定义节点:

public class Person {
    private int no;
    private Person next;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Person getNext() {
        return next;
    }

    public void setNext(Person next) {
        this.next = next;
    }

    public Person(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Person{" +
                "no=" + no +
                '}';
    }
}

测试类:

 public static void main(String[] args) {
        Person p1 = new Person(3);
        Person p2 = new Person(1);
        Person p3 = new Person(5);

        LinkedListStack stack = new LinkedListStack();
        stack.push(p1);
        stack.push(p2);
        stack.push(p3);
        stack.show();
//        stack.pop();
//        stack.pop();

    }

 

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值