Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场

Stack

作者头像
若与
发布于 2021-05-06 08:25:26
发布于 2021-05-06 08:25:26
50300
代码可运行
举报
运行总次数:0
代码可运行

stack

下面看下Java的stack源码, 具体API使用,我就不介绍了。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/*
 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.util;

/**
 * The <code>Stack</code> class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
 * operations that allow a vector to be treated as a stack. The usual
 * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
 * method to <tt>peek</tt> at the top item on the stack, a method to test
 * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
 * the stack for an item and discover how far it is from the top.
 * <p>
 * When a stack is first created, it contains no items.
 *
 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *
 * @author  Jonathan Payne
 * @since   JDK1.0
 */
public
class Stack<E> extends Vector<E> {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly
     * the same effect as:
     * <blockquote><pre>
     * addElement(item)</pre></blockquote>
     *
     * @param   item   the item to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
        addElement(item);

        return item;
    }

    /**
     * Removes the object at the top of this stack and returns that
     * object as the value of this function.
     *
     * @return  The object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it
     * from the stack.
     *
     * @return  the object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     *
     * @return  <code>true</code> if and only if this stack contains
     *          no items; <code>false</code> otherwise.
     */
    public boolean empty() {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack.
     * If the object <tt>o</tt> occurs as an item in this stack, this
     * method returns the distance from the top of the stack of the
     * occurrence nearest the top of the stack; the topmost item on the
     * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
     * method is used to compare <tt>o</tt> to the
     * items in this stack.
     *
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value <code>-1</code>
     *          indicates that the object is not on the stack.
     */
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}

由于直接使用 Vector API接口,所以很简单。

比如,底层数据扩容等,都没有介绍,如果感兴趣,可以底层源码看看,也很简单。

下面使用 go 实现一个

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package stack

import (
    "container/list"
)

// stack struct
type Stack struct {
    list *list.List
}

// get a stack
func NewStack() *Stack {
    list := list.New()
    return &Stack{list}
}

// stack method
// push  list back end
func (s *Stack) Push(value interface{}) {
    s.list.PushBack(value)
}

// pop  back element
func (s *Stack) Pop() interface{} {
    e := s.list.Back()
    if e != nil {
        s.list.Remove(e)
        return e.Value
    }
    return nil

}

func (s *Stack) Peek() interface{} {
    e := s.list.Back()
    if e != nil {
        return e.Value
    }
    return nil
}

func (s *Stack) Len() int {
    return s.list.Len()
}

func (s *Stack) Empty() bool {
    return s.list.Len() == 0
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
栈:我们能干的事情多着呢
老师:同学们大家好,这些节课我们来讲一下栈。那么什么是栈呢。栈是一种后进先出的线性表,它是按照后进先出的原则存储数据。Last In First Out ,简称LIFO,是只能在某一端也就是栈顶插入和删除的特殊的线性表,而栈的底部是不可操作的。
我的小碗汤
2018/08/22
3510
栈:我们能干的事情多着呢
集合系列 List(五):Stack
Stack 是先进后出的栈结构,其并不直接实现具体的逻辑,而是通过继承 Vector 类,调用 Vector 类的方法实现。
陈树义
2019/08/27
3020
栈(Stack源码分析)
本文所述是站在数据结构的角度。 栈可以通过链表和数组实现,先看通过数组实现的方式。
曾大稳
2018/09/11
5850
栈(Stack源码分析)
java集合【13】——— Stack源码分析走一波
前面已经把Vector,ArrayList,LinkedList分析完了,本来是想开始Map这一块,但是看了下面这个接口设计框架图:整个接口框架关系如下(来自百度百科):
秦怀杂货店
2022/01/10
2260
Java 集合深入理解(13):Stack 栈
本文通过分析Java中的栈和栈顶元素,总结出了Java集合框架中的Stack以及其使用方法,并给出示例代码。同时还介绍了如何利用LinkedList实现栈,以及具体的操作方法。
张拭心 shixinzhang
2018/01/05
1.1K0
Java 集合深入理解(13):Stack 栈
Stack-栈的源码分析与实现
Stack,栈,也是数据结构的一种,对于java应用开发者而言,我使用栈的应用场景比较少,一般做做算法类的题会用到,对于实际的应用场景我觉得栈还是比较厉害的一种数据结构,栈的特点嘛,先进后出,后进先出。
码农王同学
2020/12/25
5420
java进阶|Stack源码解析和理解
Stack这个数据结构还是比较容易理解的,满足LIFO,即先进后出,看下它的结构图,然后分析一下源码进行理解一下。
码农王同学
2020/04/09
4630
C++编程辅导:CSCI104 Stack Implementation
Implement a templated Stack class. It must implement the following interface (abstract class), which you should inherit from. In other words, create a file IStack.h which contains this definition, and then your own class (which may be called something like ListStack or ArrayStack or other, depending on how you impement it) should inherit publicly from IStack.
拓端
2022/10/25
2100
JDK 中的栈竟然是这样实现的?
前面的文章《动图演示:手撸堆栈的两种实现方法!》我们用数组和链表来实现了自定义的栈结构,那在 JDK 中官方是如何实现栈的呢?接下来我们一起来看。
磊哥
2020/10/15
4660
JDK 中的栈竟然是这样实现的?
队列实现栈有妙招
https://leetcode-cn.com/problems/implement-stack-using-queues/
代码随想录
2021/07/16
2100
232.Implement Queue using Stacks(Stack-Easy)
该文介绍了如何使用两个栈来实现队列,包括入队、出队、查看队首元素和判断队列是否为空等操作。
Jack_Cui
2018/01/08
4240
C++第十三弹 -- STL之stack深度剖析与模拟实现
在现代C++编程中,STL(标准模板库)是一个不可或缺的工具。它提供了一套通用的模板类和算法,使得开发者能够更加高效地处理数据。本文将重点介绍STL中的stack容器,作为一种重要的顺序容器,stack遵循后进先出(LIFO,Last In First Out)的特性,广泛应用于函数调用、表达式求值等场景。通过深入了解stack的特性、基本操作及应用实例,读者将能够更好地掌握和应用这一重要的数据结构。
用户11317877
2024/10/16
1350
C++第十三弹 -- STL之stack深度剖析与模拟实现
Stack Stracture
Because stack是Last in first out. 因此数组的index是0最适合做栈底, 因为变化最小
CoffeeLand
2020/03/04
3880
Stack学习-Java快速进阶教程
栈是按后进先出 (LIFO) 顺序存储的元素的集合。换句话说,栈是一种以后进先出的方式存储数据的数据结构。
jack.yang
2025/04/05
480
Stack学习-Java快速进阶教程
LeetCode 0225 - Implement Stack using Queues
Implement the following operations of a stack using queues.
Reck Zhang
2021/08/11
2760
Leetcode 232. Implement Queue using Stacks
Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must
triplebee
2018/01/12
4960
超超超高频面试题,秋招持续发力!
前两期已经有题目命中面试题了,美团面试官直接拿第一期的「搜索螺旋数组」来问我,还好写出来了。
ACM算法日常
2021/09/28
6210
Java Review - LinkedList源码解读
从上图可知: LinkedList同时实现了List接口和Deque接口,既可以看作一个顺序容器,又可以看作一个队列(Queue),同时又可以看作一个栈(Stack) 。
小小工匠
2021/11/15
2450
[搞懂Java集合类1]ArrayList,Vector与Stack
本文非常详尽地介绍了Java中的三个集合类 ArrayList,Vector与Stack
Java技术江湖
2019/09/25
7490
225. Implement Stack using Queues(Stack-Easy)
该文讲述了如何使用队列实现栈,包括push(x)、pop()、top()和empty()等操作。具体实现方式是在类中定义一个队列,在push(x)操作中,将元素x插入到队列尾部,然后依次将队列头部的元素弹出并插入到队列尾部,实现栈的操作。在pop()、top()和empty()操作中,只需要对应地操作队列即可。
Jack_Cui
2018/01/08
4810
相关推荐
栈:我们能干的事情多着呢
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验