算法通关村-----如何基于数组和链表实现栈

实现栈的基本方法

push(T t)元素入栈

T pop() 元素出栈

Tpeek() 查看栈顶元素

boolean isEmpty() 栈是否为空

基于数组实现栈

java 复制代码
import java.util.Arrays;

public class ArrayStack<T> {
    private Object[] stack;
    private int top;

    public ArrayStack() {
        this.stack = new Object[10];
        this.top = 0;
    }

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

    public void expand(int size) {
        int len = stack.length;
        if (size > len) {
            size = size * 3 / 2 + 1;
            stack = Arrays.copyOf(stack, size);
        }
    }

    public T pop() {
        T t = null;
        if (top > 0) {
            t = (T) stack[top--];
        }
        return t;
    }

    public void push(T t) {
        expand(top + 1);
        stack[top++] = t;
    }
    
    public T peek(){
        T t = null;
        if(top >0){
            t = (T) stack[top-1];
        }
        return t;
    }
}

基于链表实现栈

java 复制代码
public class ListStack<T>{
    class Node<T> {
        public T t;
        public Node next;
    }
    private Node<T> head;

    public ListStack() {
    }
    
    public boolean isEmpty() {
        if(head == null){
            return true;
        }
        return false;
    }
    
    public void push(T t){
        if(head == null){
            head = new Node<T>();
            head.t = t;
            head.next = null;
        }
        Node<T> temp = new Node<T>();
        temp.t = t;
        temp.next = head;
        head = temp;
    }
    
    public T pop() {
        if(isEmpty()){
            return null;
        }
        T t = head.t;
        head = head.next;
        return t;
    }
    
    public T peek(){
        if(isEmpty()){
            return null;
        }
        T t = head.t;
        return t;
    }
}
相关推荐
NAGNIP4 小时前
万字长文!回归模型最全讲解!
算法·面试
之歆4 小时前
Spring AI入门到实战到原理源码-MCP
java·人工智能·spring
知乎的哥廷根数学学派4 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
yangminlei4 小时前
Spring Boot3集成LiteFlow!轻松实现业务流程编排
java·spring boot·后端
qq_318121594 小时前
互联网大厂Java面试故事:从Spring Boot到微服务架构的技术挑战与解答
java·spring boot·redis·spring cloud·微服务·面试·内容社区
J_liaty4 小时前
Spring Boot整合Nacos:从入门到精通
java·spring boot·后端·nacos
阿蒙Amon5 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
daidaidaiyu5 小时前
Spring IOC 源码学习 一文学习完整的加载流程
java·spring
666HZ6665 小时前
数据结构2.0 线性表
c语言·数据结构·算法
2***d8856 小时前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端