Skip to content

Instantly share code, notes, and snippets.

@gowoonsori
Created January 26, 2021 07:13
Show Gist options
  • Save gowoonsori/2f3b60e12cbca6e00e84beaf0a4fa4a5 to your computer and use it in GitHub Desktop.
Save gowoonsori/2f3b60e12cbca6e00e84beaf0a4fa4a5 to your computer and use it in GitHub Desktop.
Java를 이용해 int배열로 Stack 구현해보기
package javaStudy.Stack;
public interface Stack {
boolean push(int data);
int pop();
}
package javaStudy.Stack;
public class UseIntArrayStack implements Stack{
private int[] stack;
private int top;
public UseIntStack(int size){
this.stack = new int[size];
this.top = -1;
}
public int getData(int idx){
return this.stack[idx];
}
@Override
public boolean push(int data) {
if(top == stack.length-1){
return false;
}
stack[++top] = data;
return true;
}
@Override
public int pop() {
if(top == -1 ){
System.out.println("Stack이 비었습니다.");
return -1;
}
return stack[top--];
}
}
package test.Stack;
import javaStudy.Stack.UseIntStack;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class useIntArrayTest {
UseIntArrayStack useIntStack;
@BeforeEach
void init(){
useIntStack = new UseIntStack(10);
}
@Test
void pushTest(){
boolean result = true;
for(int i=0; i < 10; i++){
result = useIntStack.push(i);
}
for(int i=0; i < 10; i++){
Assertions.assertEquals(i,useIntStack.getData(i));
}
Assertions.assertTrue(result);
}
@Test
void pushExceptionTest(){
boolean result = true;
for(int i=0; i < 12; i++){
result = useIntStack.push(i);
}
Assertions.assertFalse(result);
}
@Test
void removeEmptyTest(){
int result = useIntStack.pop();
Assertions.assertEquals(-1,result);
}
@Test
void removeTest(){
for(int i=0; i < 10; i++){
useIntStack.push(i);
}
int result = useIntStack.pop();
Assertions.assertEquals(9,result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment