Get the App
SLTechnology News&Howtos  ›  Development  › 

How to correctly implement the data structure stack

Shulou Source: shulou.com Published: 2022-06-03 06:30:31 09月16日 Update

This article mainly explains "how to correctly implement the data structure stack". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's study and learn "how to correctly implement the data structure stack"!

Brief introduction to Stack

Stacks (stack) only allow adding data (push) and removing data (pop) at one end of an ordered linear data set (called top stack top). Therefore, it operates according to the principle of last-in, first-out (LIFO, Last In First Out). In the stack, both push and pop operations take place at the top of the stack.

The stack is often implemented by one-dimensional array or linked list, the stack implemented by array is called sequential stack, and the stack implemented by linked list is called chained stack.

For example: just like folding plates, the last plate is always on the top, and when you take the plate, you take it from the top, that is, you take the plate that you put on it first, and the last plate is the first to be put.

Array implementation

For arrays, the process of simulating the stack is simple, because the stack is last-in, first-out, and we can easily insert and delete at the end of the array. So we chose the end as the top of the stack.

/ * stack array implementation * * @ author ervin * @ Date 2021-4-20 * / public class ArrayStack {private Object [] data; / / Top stack private int top; public ArrayStack (int size) {this.data = new Object [size]; this.top =-1;} public boolean isEmpty () {return this.top = =-1 } public boolean isFull () {return this.top = = data.length-1;} public void push (T t) throws Exception {if (isFull ()) {/ / expand Object [] newDate = new Object [top * 2]; for (int I = 0; I

Tags: Character data string parenthesis array page plate data structure structure valid backward node problem order first out learning two element content function Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Linux Huawei macOS OPPO Reno