File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed
src/main/java/com/thealgorithms/stacks Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .stacks ;
2+
3+ class Node <T > {
4+ T data ;
5+ Node <T > next ;
6+
7+ public Node (T data ) {
8+ this .data = data ;
9+ this .next = null ;
10+ }
11+ }
12+
13+ public class StackUsingLinkedList <T > {
14+ private Node <T > top ;
15+ private int size ;
16+
17+ public StackUsingLinkedList () {
18+ top = null ;
19+ size = 0 ;
20+ }
21+
22+ // Push operation
23+ public void push (T data ) {
24+ Node <T > temp = new Node <>(data );
25+ temp .next = top ;
26+ top = temp ;
27+ size ++;
28+ }
29+
30+ // Pop operation
31+ public T pop () {
32+ if (top == null ) {
33+ throw new RuntimeException ("Stack Underflow" );
34+ }
35+ T value = top .data ;
36+ Node <T > temp = top ;
37+ top = top .next ;
38+ temp .next = null ; // help GC
39+ size --;
40+ return value ;
41+ }
42+
43+ // Peek operation
44+ public T peek () {
45+ if (top == null ) {
46+ throw new RuntimeException ("Stack is empty" );
47+ }
48+ return top .data ;
49+ }
50+
51+ // Size operation (O(1))
52+ public int size () {
53+ return size ;
54+ }
55+ public boolean isEmpty () {
56+ return size == 0 ;
57+ }
58+ }
59+ class demo {
60+ public static void main (String [] args ) {
61+ StackUsingLinkedList <Integer > stack = new StackUsingLinkedList <>();
62+
63+ System .out .println ("Is stack empty? " + stack .isEmpty ());
64+ System .out .println ("Initial size: " + stack .size ());
65+
66+
67+ stack .push (10 );
68+ stack .push (20 );
69+ stack .push (30 );
70+
71+ System .out .println ("After pushes:" );
72+ System .out .println ("Top element: " + stack .peek ()); // 30
73+ System .out .println ("Size: " + stack .size ()); // 3
74+
75+ // Pop elements
76+ System .out .println ("Popped: " + stack .pop ()); // 30
77+ System .out .println ("Popped: " + stack .pop ()); // 20
78+
79+ System .out .println ("After pops:" );
80+ System .out .println ("Top element: " + stack .peek ()); // 10
81+ System .out .println ("Size: " + stack .size ()); // 1
82+
83+ System .out .println ("Is stack empty? " + stack .isEmpty ());
84+
85+
86+ stack .pop ();
87+ System .out .println ("Is stack empty after final pop? " + stack .isEmpty ());
88+ }
89+ }
You can’t perform that action at this time.
0 commit comments