diff --git a/Exercise_1.java b/Exercise_1.java index 314a3cb45..2624370f0 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,35 +1,71 @@ class Stack { //Please read sample.java file before starting. //Kindly include Time and Space complexity at top of each file +// Time Complexity for push operation: O(1) + + // Time Complexity for pop operation : O(1) + + //Time Complexity for peek operation : O(1) + + //Space Complexity is O(n) since it has a constant space to store n elements + + // Its difficult to understamd how to start working on the problem but once I got idea its easy to implement + static final int MAX = 1000; - int top; - int a[] = new int[MAX]; // Maximum size of Stack + int top = -1; + int[] a; + boolean isEmpty() { - //Write your code here + if(top == -1) { + return true; + + } + return false; + } Stack() { - //Initialize your constructor + a = new int[MAX]; } boolean push(int x) { //Check for stack Overflow //Write your code here + + if(top == MAX-1){ + throw new Error("Stack overflow exception"); + } + a[top +1 ] = x; + top++; + return true; } int pop() { //If empty return 0 and print " Stack Underflow" //Write your code here + if(top == -1){ + System.out.println("Stack Underflow"); + return 0; + + } + + return a[top--]; + + } int peek() { - //Write your code here + + if(top == -1){ + throw new Error("Empty Stack Exception"); + } + return a[top]; } } diff --git a/Exercise_2.java b/Exercise_2.java index 5a9c4868c..c7ac06e3a 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -8,19 +8,22 @@ static class StackNode { StackNode(int data) { - //Constructor here + this.data = data; + + } } - public boolean isEmpty() - { - //Write your code here for the condition if stack is empty. - } + public void push(int data) { //Write code to push data to the stack. + + StackNode newNode = new StackNode(data); + newNode.next = root; + root = newNode; } public int pop() @@ -28,11 +31,27 @@ public int pop() //If Stack Empty Return 0 and print "Stack Underflow" //Write code to pop the topmost element of stack. //Also return the popped element + + if(root == null) { + System.out.println("Stack Underflow"); + return 0; + } + + int returnData = root.data; + + root = root.next; + return returnData; + } public int peek() { //Write code to just return the topmost element without removing it. + + if(root != null){ + return root.data; + } + return -1; } //Driver code