模拟实现栈和队列中的常用方法

模拟实现栈和队列中的常用方法

概念

栈:是一种特殊的线性表,只允许在固定的一端进行插入和删除元素操作。进行插入和删除的叫做栈顶,另一端叫做栈底。栈遵循先进后出(FILO)、后进先出(LIFO) 原则。

方法

在Java中,对于栈提供了如下方法:
在这里插入图片描述

返回值类型方法名作用
booleanempty()判断栈是否为空
Epeek()查看栈顶元素
Epop()出栈,并返回出栈元素
Epush(E)入栈

模拟实现栈

可以用ArraysList使用尾插\尾删的方式实现模拟实现栈
也可以用LinkedList使用头插\头删或者尾插\尾删的方式实现

我们就使用数组来模拟实现栈:

public class MyStack {
    //暂时先不考虑扩容问题
    private int[] array = new int[100];
    private int size = 0;

    public void push(int v) {
        array[size] = v;
        size++;
    }

    public int pop() {
        int ret = array[size - 1];
        size--;
        return ret;
    }

    public int peek() {
        return array[size - 1];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }
}

队列

概念

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出(FIFO) 的原则。

方法

在Java中,对于队列提供了如下方法:
在这里插入图片描述

返回值类型方法名作用
booleanadd()\offer()入队列
Eremove()\poll()出队列
Eelement()\peek()队首元素

模拟实现队列

队列也可以用数组和链表来实现,但是链表的话结构更优一些。如果是数组,那么每次出队列或者入队列,在数组头部,效率比较低。

使用链表模拟实现队列。
尾插,头删

//结点类
class Node {
    int val;
    Node next;

    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }

    public Node(int val) {
        this(val, null);
    }
}

public class MyQueue {
    private Node head = null;
    private Node tail = null;
    private int size = 0;

    public void add(int v) {
        Node node = new Node(v);
        if (tail == null) {
            head = node;
        } else {
            tail.next = node;
        }
        tail = node;
        size++;
    }

    public int poll() {
        if (size() == 0) {
            throw new RuntimeException("队列为空");
        }
        int ret = head.val;
        head = head.next;
        if (head == null) {
            tail = null;
        }
        size--;
        return ret;
    }

    public int peek() {
        if (size() == 0) {
            throw new RuntimeException("队列为空");
        }
        return head.val;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }
}
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

无赖H4

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

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

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

打赏作者

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

抵扣说明:

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

余额充值