Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Created August 7, 2022 22:07
Show Gist options
  • Save alexandreaquiles/5553836c35b69588c9e1688ddfbc6060 to your computer and use it in GitHub Desktop.
Save alexandreaquiles/5553836c35b69588c9e1688ddfbc6060 to your computer and use it in GitHub Desktop.
Stack Cluster Operation from Liskov's ADT paper
package adt;
import java.util.Arrays;
public class Stack<E> {
private int tp;
private E[] stk;
public Stack() {
tp = 0;
stk = (E[]) new Object[1];
}
public void push(E v) {
if (tp == stk.length) {
stk = Arrays.copyOf(stk, stk.length * 2);
}
stk[tp] = v;
tp = tp + 1;
}
public E pop() {
if (tp == 0) {
throw new RuntimeException();
}
tp = tp - 1;
return stk[tp];
}
public E top() {
if (tp == 0) {
throw new RuntimeException();
}
return stk[tp-1];
}
public void eraseTop() {
if (tp == 0) {
throw new RuntimeException();
}
tp = tp - 1;
}
public boolean empty() {
return tp == 0;
}
}
package adt;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StackTest {
@Test
void new_stack_should_be_empty() {
var s = new Stack<String>();
assertTrue(s.empty());
}
@Test
void new_stack_should_throw_error_when_trying_to_pop() {
var s = new Stack<String>();
assertThrows(RuntimeException.class, () -> {
s.pop();
});
}
@Test
void new_stack_should_throw_error_when_trying_to_top() {
var s = new Stack<String>();
assertThrows(RuntimeException.class, () -> {
s.top();
});
}
@Test
void new_stack_should_throw_error_when_trying_to_eraseTop() {
var s = new Stack<String>();
assertThrows(RuntimeException.class, () -> {
s.eraseTop();
});
}
@Test
void pop_removes_the_element() {
var s = new Stack<String>();
s.push("banana");
String element = s.pop();
assertEquals("banana", element);
assertTrue(s.empty());
}
@Test
void top_returns_the_element_but_doesnt_remove() {
var s = new Stack<String>();
s.push("banana");
String element = s.top();
assertEquals("banana", element);
assertFalse(s.empty());
}
@Test
void eraseTop_remove_but_doesnt_return() {
var s = new Stack<String>();
s.push("banana");
s.eraseTop();
assertTrue(s.empty());
}
@Test
void pop_is_lifo() {
var s = new Stack<String>();
s.push("banana");
s.push("apple");
String element = s.pop();
assertEquals("apple", element);
assertFalse(s.empty());
String anotherElement = s.pop();
assertEquals("banana", anotherElement);
assertTrue(s.empty());
}
@Test
void top_is_lifo() {
var s = new Stack<String>();
s.push("banana");
s.push("apple");
String element = s.top();
assertEquals("apple", element);
assertFalse(s.empty());
}
@Test
void eraseTop_is_lifo() {
var s = new Stack<String>();
s.push("banana");
s.push("apple");
s.eraseTop();
String element = s.top();
assertEquals("banana", element);
assertFalse(s.empty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment