Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.thealgorithms.stacks;

class Node<T> {
T data;
Node<T> next;

public Node(T data) {
this.data = data;
this.next = null;
}
}

public class StackUsingLinkedList<T> {
private Node<T> top;
private int size;

public StackUsingLinkedList() {
top = null;
size = 0;
}

// Push operation
public void push(T data) {
Node<T> 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<T> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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<Integer> 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());
}
}
Loading