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

实现栈的基本方法

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;
    }
}
相关推荐
湖北二师的咸鱼7 分钟前
c#和c++区别
java·c++·c#
weixin_4180076015 分钟前
软件工程的实践
java
汪子熙22 分钟前
在 Word 里编写 Visual Basic 调用 DeepSeek API
后端·算法·架构
什么半岛铁盒39 分钟前
Linux中INADDR_ANY详解
开发语言·c++·算法
物联网嵌入式小冉学长1 小时前
2.线性表的链式存储-链表
数据结构·链表
顾小玙1 小时前
前缀和:leetcode974--和可被K整除的子数组
数据结构·算法
lpfasd1231 小时前
备忘录模式(Memento Pattern)
java·设计模式·备忘录模式
迢迢星万里灬1 小时前
Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术点解析
java·spring boot·spring·mybatis·spring mvc·面试指南
代码丰1 小时前
使用Spring Cloud Stream 模拟生产者消费者group destination的介绍(整合rabbitMQ)
java·分布式·后端·rabbitmq