Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Exercise_2.java #1986

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
28 changes: 24 additions & 4 deletions Exercise_2.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Time Complexity: O(1)
// Space Complexity: O(n)
public class StackAsLinkedList {

StackNode root;
Expand All @@ -8,31 +10,49 @@ static class StackNode {

StackNode(int data)
{
//Constructor here
this.data = data;
this.next = null;
}
}


public boolean isEmpty()
{
//Write your code here for the condition if stack is empty.
return root == null;
}

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 (isEmpty()) {
System.out.println("Stack Underflow");
return Integer.MIN_VALUE;
}

int popped = root.data;
root = root.next;
return popped;
}



public int peek()
{
//Write code to just return the topmost element without removing it.
if (isEmpty()) {
System.out.println("No elements to peek");
return Integer.MIN_VALUE;
}
return root.data;
}

//Driver code
Expand Down