Last active
December 19, 2021 10:26
-
-
Save sunmeat/b2464c75fd020af3d155c2c0b108e23b to your computer and use it in GitHub Desktop.
simple array stack example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package collections; | |
class Stack { | |
private int max = 10; | |
private int[] ar; | |
private int top = 0; // индекс вершины стека | |
// а заодно, и количество элементов в нём | |
public Stack() { | |
ar = new int[max]; | |
} | |
public void clear() { | |
top = 0; | |
} | |
public boolean isEmpty() { | |
return top == 0; | |
} | |
public boolean isFull() { | |
return top == max; | |
} | |
public int getCount() { | |
return top; | |
} | |
// заталкивание | |
public void push(int value) { | |
if (!isFull()) { | |
ar[top] = value; | |
top++; | |
} | |
} | |
// выталкивание | |
public int pop() { | |
if (!isEmpty()) { | |
top--; | |
return ar[top]; | |
} else { | |
return -1; | |
} | |
} | |
} | |
class Program { | |
public static void main(String[] args) { | |
Stack st = new Stack(); | |
st.push(10); | |
st.push(20); | |
st.push(30); | |
System.out.println(st.pop()); | |
System.out.println(st.pop()); | |
int temp = st.pop(); | |
System.out.println(temp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment