栈的简单实现

什么是栈?

  1. 栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
  2. 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
  3. 出栈:栈的删除操作叫做出栈。出数据在栈顶。

栈的实现

  1. 这里用顺序表来实现
public class MyStack {
	private int[] array = new int[100];
	private int size = 0;
	
	public void push(int v) {
		array[size++] = v;
	}
	public int pop() {
		return array[--size];
	}
	public int peek() {
		return array[size - 1];
	}
	public boolean isEmpty() {
		return size == 0;
	}
	public int size() {
		return size;
	}
}
  1. 用链表来实现
public class MyStack {
    Node cur;
    class Node{
        private int val;
        private Node next;
        public Node(int val) {
            this.val = val;
        }
    }


    public void push(int v){
        Node node = new Node(v);
        if(this.cur == null){
            this.cur = node;
        }
        node.next = this.cur;
        this.cur = node;
    }


    public int pop() {
        if(isEmpty()){
            throw new RuntimeException("栈为空!");
        }
        int data = this.cur.val;
        this.cur = cur.next;
        return data;
    }


    public int peek() {
        if(isEmpty()){
            throw new RuntimeException("栈为空!");
        }
        return this.cur.val;
    }


    public boolean isEmpty() {
        return this.cur == null;
    }


    public int size() {
        int size = 0;
        Node head = this.cur;
        if(head == null){
            return size;
        }
        while(head != null){
            size++;
            head = head.next;
        }
        return size;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Matinal_01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值