diff --git a/src/main/java/com/thealgorithms/stacks/StackUsingLinkedList.java b/src/main/java/com/thealgorithms/stacks/StackUsingLinkedList.java new file mode 100644 index 000000000000..8dd2825b9f2d --- /dev/null +++ b/src/main/java/com/thealgorithms/stacks/StackUsingLinkedList.java @@ -0,0 +1,58 @@ +package com.thealgorithms.stacks; + +class Node { + T data; + Node next; + + public Node(T data) { + this.data = data; + this.next = null; + } +} + +public class StackUsingLinkedList { + private Node top; + private int size; + + public StackUsingLinkedList() { + top = null; + size = 0; + } + + // Push operation + public void push(T data) { + Node temp = new Node<>(data); + temp.next = top; + top = temp; + size++; + } + + // Pop operation + public T pop() { + if (top == null) { + throw new RuntimeException("Stack Underflow"); + } + T value = top.data; + Node temp = top; + top = top.next; + temp.next = null; // help GC + size--; + return value; + } + + // Peek operation + public T peek() { + if (top == null) { + throw new RuntimeException("Stack is empty"); + } + return top.data; + } + + // Size operation (O(1)) + public int size() { + return size; + } + public boolean isEmpty() { + return size == 0; + } +} diff --git a/src/test/java/com/thealgorithms/stacks/StackUsingLinkedListTest.java b/src/test/java/com/thealgorithms/stacks/StackUsingLinkedListTest.java new file mode 100644 index 000000000000..38ab52c8f8a1 --- /dev/null +++ b/src/test/java/com/thealgorithms/stacks/StackUsingLinkedListTest.java @@ -0,0 +1,57 @@ +package com.thealgorithms.stacks; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + + + +public class StackUsingLinkedListTest { + private StackUsingLinkedList stack; + + @BeforeEach + public void setUp() { + stack = new StackUsingLinkedList<>(); + } + + @Test + public void testPushAndPeek() { + stack.push(10); + stack.push(20); + + assertEquals(20, stack.peek()); + } + + @Test + public void testPop() { + stack.push(5); + stack.push(15); + int popped = stack.pop(); + assertEquals(15, popped); + assertEquals(5, stack.peek()); + } + + @Test + public void testIsEmpty() { + assertTrue(stack.isEmpty()); + stack.push(1); + assertFalse(stack.isEmpty()); + } + + @Test + public void testSize() { + assertEquals(0, stack.size()); + stack.push(1); + stack.push(2); + assertEquals(2, stack.size()); + } + + @Test + public void testPopOnEmptyStack() { + assertThrows(RuntimeException.class, () -> stack.pop()); + } + @Test + public void testPeekOnEmptyStackThrowsException() { + RuntimeException exception = assertThrows(RuntimeException.class, () -> stack.peek()); + assertEquals("Stack is empty", exception.getMessage()); + } +}