From 2686ba31b75faf2bb8d64d012a6262773ea63b5e Mon Sep 17 00:00:00 2001 From: VasundharaVenkataKrishna Date: Sat, 19 Oct 2024 12:34:38 -0500 Subject: [PATCH] Update Exercise_2.java --- Exercise_2.java | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/Exercise_2.java b/Exercise_2.java index 5a9c4868c..9165f4437 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -1,3 +1,5 @@ +// Time Complexity: O(1) +// Space Complexity: O(n) public class StackAsLinkedList { StackNode root; @@ -8,19 +10,22 @@ 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() @@ -28,11 +33,26 @@ 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