-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingArray.java
More file actions
105 lines (96 loc) · 2.91 KB
/
Copy pathStackUsingArray.java
File metadata and controls
105 lines (96 loc) · 2.91 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.ds.rani.design;
/**
* Implement stack using Array
*/
class Stack {
int stackSize;
int top;
int a[];
/**
* Constructor
*/
Stack(int size) {
stackSize = size;
top = -1;
a = new int[stackSize];
}
/**
* check whether stack is empty or not
*
* @return true if stack is empty and false if not.
*/
//Time Complexity:o(1)
// Space complexity:o(1)
boolean isEmpty() {
//if top is at -1 it means stack is empty
return top == -1;
}
/**
* Push the value x into stack and returns boolean value
*
* @param x : int value
* @return returns true if stack has a space and inserts value in a stack else returns false
*/
//Time Complexity:o(1)
// Space complexity:o(1)
boolean push(int x) {
//There is a space available in the stack for new element
if (top + 1 < stackSize) {
top++;
a[top] = x;
return true;
} else {
//element is not pushed because of stack overflow
System.out.println( " Stack OverFlow" );
return false;
}
}
/**
* pop or remove the elemnt from the stack. If stack doesnt have ny elemnt then print Stack
* underflow and return 0. else remove the top value return it
*
* @return
*/
//Time Complexity:o(1)
// Space complexity:o(1)
int pop() {
//If stack is empty
if (isEmpty()) {
System.out.println( " Stack Underflow" );
return 0;
} else {
return a[top--];
}
}
/**
* Return the top value of the stack.If stack is empty return 0 else return top element
*
* @return int value
*/
//Time Complexity:o(1)
// Space complexity:o(1)
int peek() {
if (isEmpty()) {
return 0;
} else {
return a[top];
}
}
}
public class StackUsingArray {
public static void main(String args[])
{
Stack s = new Stack(100);
System.out.println("Peek():"+s.peek());
System.out.println("pop():"+s.pop());
System.out.println("Stack Empty:"+s.isEmpty());
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
System.out.println("Stack Empty:"+s.isEmpty());
System.out.println(s.pop() + " Popped from stack");
System.out.println(s.pop() + " Popped from stack");
System.out.println("Stack Empty:"+s.isEmpty());
}
}