Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Juan Sedano
Juan Sedano

Posted on • Originally published atjsedano.dev on

     

Stack

My notes on thestack abstract data type with an implementation using an array in Java.

You can find the complete code for this and other data structures here:data structures and algorithms

Astack is anabstract data type that mimics a real world stack where you can place elements on the top or you can take the top element. The behavior of the stack is described aslast in first out (LIFO).

Common Operations for a stack includes:

OperationComplexity
push(element)O(1)
pop()O(1)

Push will place a new element on the top of the stack.

node

public boolean push(T valueToPush) {    if(size == innerArray.length) {        return false;    }    innerArray[size] = valueToPush;    size++;    return true;}
Enter fullscreen modeExit fullscreen mode

Pop takes out the top element from the stack and returns it.

node

public T pop() {    if(size == 0) {        throw new NullPointerException("empty stack");    }    T valueToPop = innerArray[size - 1];    innerArray[size - 1] = null;    size--;    return valueToPop;}
Enter fullscreen modeExit fullscreen mode

In this implementation thecapacity of the stack is the capacity of theinner array. We keep track of the size of the stack by increasing or decreasing the size with every pop and push, by doing this we always know thattop is atinnerArray[size-1] and when we do a push we put new element atinnerArray[size].

Implementing a stack using alinked list would be even easier because we can keep prepending a new node to the linked list with every push and for the pop we only need to get the first element, remove it from the list and then return it.

Download the complete code for this and other data structures here:data structures and algorithms.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi! I just want to learn and share : )
  • Location
    Guadalajara, México
  • Work
    Tech lead at Clip
  • Joined

More fromJuan Sedano

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp