Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions Exercise_1.java
Original file line number Diff line number Diff line change
@@ -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];
}
}

Expand Down
29 changes: 24 additions & 5 deletions Exercise_2.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,50 @@ 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()
{
//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
Expand Down