forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_1.cs
74 lines (68 loc) · 1.91 KB
/
Exercise_1.cs
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
class Stack {
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this :
static int MAX = 1000;
int top;
int[] a = new int[MAX]; // Maximum size of Stack
// Time Complexity : O(1)
// Space Complexity : O(1)
public bool IsEmpty()
{
//Write your code here
return top == -1;
}
public Stack()
{
//Initialize your constructor
top = -1;
}
// Time Complexity : O(1)
// Space Complexity : O(1)
public bool Push(int x)
{
//Check for stack Overflow
//Write your code here
if(++top < MAX){
a[top] = x;
return true;
} else{
top--;
System.Console.WriteLine("Stack Overflow");
return false;
}
}
// Time Complexity : O(1)
// Space Complexity : O(1)
public int Pop()
{
//If empty return 0 and print " Stack Underflow"
//Write your code here
if(top<0)
{
System.Console.WriteLine("Stack Underflow");
return 0;
} else {
int temp = a[top];
top --;
return temp;
}
}
// Time Complexity : O(1)
// Space Complexity : O(1)
public int Peek()
{
//Write your code here
return IsEmpty() ? 0 : a[top];
}
}
// Driver code
class Main {
public static void main(String[] args)
{
Stack s = new Stack();
s.Push(10);
s.Push(20);
s.Push(30);
System.Console.WriteLine(s.Pop() + " Popped from stack");
}
}