Use arrays to implement stack

Last updated on January 14, 2023 pm

栈:先入后出(FILO-First In Last Out)的有序链表。top–bottom, pop–push。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//use arrays to implement stack
class ArrayStack {
private int maxSize; //size of stack
private int[] stack; //data
private int top = -1; //top of the stack, initiated as -1

//constructor
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
}

public boolean isFull() {
return top == maxSize - 1;
}

public boolean isEmpty() {
return top == -1;
}

//push
public void push(int value) {
if (isFull()) {
System.out.println("The stack has been full. Can't push new value in it.");
return;
}
top++;
stack[top] = value;
}

//pop
public int pop() {
if (isEmpty()) {
throw new RuntimeException("The stack has been empty. Can't pop.");
}

int value = stack[top];
top--;
return value;
}

//iterate (from top to bottom)
public void showStack() {
if (isEmpty()) {
System.out.println("The stack is empty.");
return;
}

for (int i = top; i >= 0; i--) {
System.out.println("stack[" + i + "] = " + stack[i]);
}
}
}

Use arrays to implement stack
http://hihiko.zxy/2023/01/14/Use-arrays-to-implement-stack/
Author
Posted on
January 14, 2023
Licensed under