22
33/**
44 * Stack implementation using a singly linked list.
5- *
5+ *
66 * @param <T> the type of elements stored in the stack
7- *
7+ *
88 * Operations:
99 * - push(T data): Insert an element onto the stack (O(1))
1010 * - pop(): Remove and return the top element (O(1))
@@ -25,17 +25,17 @@ private class Node {
2525 }
2626 }
2727
28- private Node top ; // top of the stack
29- private int size ; // number of elements in the stack
28+ private Node top ; // top of the stack
29+ private int size ; // number of elements in the stack
3030
3131 /** Constructor: Initializes an empty stack */
3232 public StackUsingLinkedList () {
3333 top = null ;
3434 size = 0 ;
3535 }
3636
37- /**
38- * Pushes an element onto the top of the stack.
37+ /**
38+ * Pushes an element onto the top of the stack.
3939 * @param data element to be pushed
4040 */
4141 public void push (T data ) {
@@ -45,7 +45,7 @@ public void push(T data) {
4545 size ++;
4646 }
4747
48- /**
48+ /**
4949 * Removes and returns the top element of the stack.
5050 * @return the popped element
5151 * @throws IllegalStateException if the stack is empty
@@ -60,7 +60,7 @@ public T pop() {
6060 return data ;
6161 }
6262
63- /**
63+ /**
6464 * Returns the top element without removing it.
6565 * @return the top element
6666 * @throws IllegalStateException if the stack is empty
@@ -72,23 +72,23 @@ public T peek() {
7272 return top .data ;
7373 }
7474
75- /**
75+ /**
7676 * Checks whether the stack is empty.
7777 * @return true if empty, false otherwise
7878 */
7979 public boolean isEmpty () {
8080 return top == null ;
8181 }
8282
83- /**
83+ /**
8484 * Returns the number of elements in the stack.
8585 * @return the size of the stack
8686 */
8787 public int size () {
8888 return size ;
8989 }
9090
91- /**
91+ /**
9292 * Prints the stack elements from top to bottom.
9393 */
9494 public void printStack () {
@@ -105,8 +105,8 @@ public void printStack() {
105105 System .out .println ();
106106 }
107107
108- /**
109- * Example usage
108+ /**
109+ * Example usage
110110 */
111111 public static void main (String [] args ) {
112112 StackUsingLinkedList <Integer > stack = new StackUsingLinkedList <>();
@@ -115,11 +115,11 @@ public static void main(String[] args) {
115115 stack .push (20 );
116116 stack .push (30 );
117117
118- stack .printStack (); // Output: 30 20 10
118+ stack .printStack (); // Output: 30 20 10
119119
120120 System .out .println ("Top element: " + stack .peek ()); // 30
121- System .out .println ("Popped: " + stack .pop ()); // 30
122- stack .printStack (); // 20 10
123- System .out .println ("Size: " + stack .size ()); // 2
121+ System .out .println ("Popped: " + stack .pop ()); // 30
122+ stack .printStack (); // 20 10
123+ System .out .println ("Size: " + stack .size ()); // 2
124124 }
125125}
0 commit comments