-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathStackDS.java
83 lines (69 loc) · 2.37 KB
/
StackDS.java
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// https://excalidraw.com/#json=ilDgfbvHd2ctypu_NokLt,yTdZu2D-Ge3c0jzRHxzXuQ
// 1. Constructors and its types, memory allocation in java
// 2. Stack DS, complexity, theory, its implementation by ourselves, Java stack library and its usage
import java.util.Scanner;
public class StackDS {
private int[] stk; // declaration, no memory allocation
private int maxSize; // declaration
private int top; // declaration
// we don't need to implement this default constructor, java automatically creates it.
// default constructor
public StackDS() {
maxSize = 100000; // definition -> allocates memory as well
top = 0; // definition -> allocates memory as well. Another way to do is use top = -1.
stk = new int[maxSize]; // definition -> allocates memory as well
}
// parametrized constructor
public StackDS(int size) {
maxSize = size;
top = 0;
stk = new int[maxSize];
}
// copy constructor
public StackDS(StackDS anotherStack) {
this.maxSize = anotherStack.maxSize;
stk = new int[maxSize];
top = 0;
}
public void push(int val) { // O(1)
// check if stack is already full
if (top == maxSize) {
// stack is full
System.out.println("stack already full");
return;
}
// put an element val on top of stack
stk[top] = val;
top++;
// if top initially is -1, stk[++top]=val;
}
public int top() { // or peek // O(1)
// check if stack is empty
if (isEmpty()) {
// stack is empty
System.out.println("stack is empty, can't see top element");
}
// return top element of stack
return stk[top-1];
// if top initially is -1, return stk[top]
}
public int pop() { // O(1)
// check if stack is empty
if (isEmpty()) {
System.out.println("stack is empty, can't pop");
}
// extrack topmost elemnt from stack
// top--;
// return stk[top];
return stk[--top];
// if top initially is -1, return stk[top--]
}
public boolean isEmpty() { // O(1)
// returns whether stack is empty or not
if (top == 0) {
return true;
}
return false;
}
// if top initially is -1, if top == -1 then stack is empty
}