Stack,Queue

用顺序表实现栈(非扩容)
顺序栈

class Stack{
    public int[] elem;
    public int usedsize;

    public Stack(){
        this.elem=new int[5];
    }

    public boolean isFull(){
       return this.usedsize==this.elem.length;
    }

    public boolean isEmpty(){
        if(usedsize==0){
            return true;
        }
        return false;
    }

    public void push(int val){
     if(isFull()){
         return;
     }
     this.elem[this.usedsize]=val;
     this.usedsize++;
    }

    public int pop(){
if(isEmpty()){
   throw new RuntimeException("栈为空");
}
int ret=this.elem[usedsize-1];
this.usedsize--;
return ret;
    }

    public int peek(){
        if(isEmpty()){
            return -1;
        }
        return this.elem[usedsize-1];
    }
}

public class TestDemo{
    public static void main(String[] args) {
        Stack stack=new Stack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop());

        System.out.println(stack.peek());
    }
}

链式栈最好用头插法,头删法 空间复杂度和时间复杂度为O(1)

链式队列

class Node {
    public Node next;
    public int val;

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

class MyQueue {
    public Node head;
    public Node tail;

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

    public int poll() {
        if (this.head == null) {
            throw new RuntimeException("队列为空!");
        }
        int data = this.head.val;
        if (this.head.next == null) {
            this.head = null;
            this.tail = null;
        } else {
            this.head = this.head.next;
        }
        return data;
    }

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

    public boolean isEmpty(){
        if(this.head==null){
            return true;
        }
        return false;
    }
}
public class TestDemo{
public static void main(String args[]){
MyQueue queue=new MyQueue();
queue.offer(1);
queue.offer(2);
queue.offer(3);
    System.out.println(queue.poll());
    System.out.println(queue.peek());
    System.out.println(queue);
}
        }

循环队列
底层是一个数组

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值