From be9be56539f0ad0b30aa737ff9c14b56c549dc63 Mon Sep 17 00:00:00 2001 From: Ayush Mitra <89930295+ayushmitra06@users.noreply.github.com> Date: Wed, 10 Jan 2024 16:54:46 +0530 Subject: [PATCH] Update StackLL.java Changes made: Removed public static from the head variable in the Stack class. Updated the push method to correctly handle the case when the stack is initially empty. Corrected the access modifiers for the Node class and head variable. --- Stack/StackLL.java | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/Stack/StackLL.java b/Stack/StackLL.java index 0f7de81..51a4f38 100644 --- a/Stack/StackLL.java +++ b/Stack/StackLL.java @@ -1,5 +1,4 @@ -//stack using Linked List -public class StackDS { +public class StackLL { private static class Node { int data; Node next; @@ -11,24 +10,25 @@ private static class Node { } static class Stack { - public static Node head = null; - public static void push(int data) { + private Node head; // Removed 'public static' from head + + public void push(int data) { Node newNode = new Node(data); - if(head == null) { + if (head == null) { + head = newNode; + } else { + newNode.next = head; head = newNode; - return; } - newNode.next = head; - head = newNode; } - public static boolean isEmpty() { + public boolean isEmpty() { return head == null; } - public static int pop() { - if(isEmpty()) { + public int pop() { + if (isEmpty()) { return -1; } Node top = head; @@ -36,12 +36,11 @@ public static int pop() { return top.data; } - public static int peek() { - if(isEmpty()) { + public int peek() { + if (isEmpty()) { return -1; } - Node top = head; - return top.data; + return head.data; } } @@ -52,9 +51,9 @@ public static void main(String args[]) { stack.push(3); stack.push(4); - while(!stack.isEmpty()) { + while (!stack.isEmpty()) { System.out.println(stack.peek()); stack.pop(); } } -} \ No newline at end of file +}