栈和队列

本文介绍了栈和队列这两种基本数据结构的实现。栈遵循后进先出(LIFO)原则,常用于表达式求值、递归等场景,而队列遵循先进先出(FIFO)原则,常用于任务调度、缓冲区管理等。文章通过Java代码展示了基于数组和链表的栈和队列实现,并提到了循环队列的概念。
摘要由CSDN通过智能技术生成

学习目标:

栈和队列


学习内容:

栈和队列也是基于List来实现的
限制比List更严格(提供的操作更少),List比栈和队列要更 灵活。

栈(Stack):

一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈
顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶
public class MyStack {
    private int[] array = new int[100];
    private int size = 0;

    //入栈
    public void push(int x){
        array[size] = x;
        size++;
    }

    //取栈顶元素
    public int peek(){
       return array[size-1];
    }

    //出栈
    public int pop(){
        int x =array[size-1];
        size--;
        return x;
    }
}

队列(Queue):

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First
In First Out) 
入队列:进行插入操作的一端称为队尾(Tail/Rear)
出队列:进行删除操作的一端称为队头(Head/Front)
public class MyQueue {
    //Node 这个类叫做“内部类”,定义在某个类或者方法的类
    //static 效果是:创建Node的实例不依赖MyQueueBYLinkedList这个类的实例
    static class Node{
        public int val;
        Node next = null;

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

    //创建一个链表
    //基于链表来实现队列,可以入队列的尾部插入,出队列从头部删除;也可以如队列从头部插入,出队列从尾部删除。
    private Node head = null;
    private Node tail = null;

    //入队列
    public void offer(int val){
        Node node = new Node(val);
        if (head == null) {
            this.head = node;
            this.tail = node;
            return;
        }
        this.tail.next = node;
        this.tail = this.tail.next;
    }

    //出队列
    public Integer pop(){
        if (head==null) return null;
        int ret = head.val;
        head = head.next;
        if(head==null){
            tail = null;
        }
        return ret;
    }

    //取队首元素
    public Integer peek(){
        if (head==null) return null;
        int x =head.val;
        head = head.next;
        if (head==null){
            tail = null;
        }
        return x;
    }
}

循环队列

public class MyQueueByArray {
    private int[] array = new int[100];
    //队首元素
    private int head = 0;

    //队尾元素
    private int tail = 0;

    //元素个数
    private int size = 0;

    //入队
    public void offer(int val) {
        if (size == array.length) return;

        array[tail] = val;
        tail++;
        if (this.tail>=array.length){
            this.tail=0;
        }
        this.size++;
    }

    //出队
    public Integer poll(){
        if (this.size == array.length) return null;

        Integer ret = array[head];
        if (this.head>=array.length){
            this.head=0;
        }
        this.size--;
        return ret;
    }

    //有效长度
    public Integer peek() {
        if (size == 0) return null;
        return array[head];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值