Skip to content

Instantly share code, notes, and snippets.

@gowoonsori
Created January 26, 2021 07:12
Show Gist options
  • Save gowoonsori/dcbc425eb254d44d01aa70da2d8995e6 to your computer and use it in GitHub Desktop.
Save gowoonsori/dcbc425eb254d44d01aa70da2d8995e6 to your computer and use it in GitHub Desktop.
Java이용해 LinkedList로 Stack구현하기
package javaStudy.ListNodeStack;
import javaStudy.ListNode.ListNode;
public class ListNodeStack implements Stack{
ListNode node;
int top;
public ListNodeStack(){
node = null;
top = 0;
}
public ListNode getNode() {
return node;
}
public int getTop() {
return top;
}
@Override
public boolean push(int data) {
if(top == 0){
node = new ListNode(data);
top++;
}
else node.add(new ListNode(data),top++);
return true;
}
@Override
public int pop() {
if(top == 0){
System.out.println("Empty");
return -1;
}
return node.remove(--top).getKey();
}
}
package test.ListNodeStack;
import javaStudy.ListNode.ListNode;
import javaStudy.ListNodeStack.ListNodeStack;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ListNodeStackTest {
ListNodeStack listNodeStack;
@BeforeEach
void init(){
listNodeStack = new ListNodeStack();
listNodeStack.push(1);
listNodeStack.push(2);
listNodeStack.push(3);
}
@Test
void add(){
listNodeStack.push(4);
ListNode node = listNodeStack.getNode();
for(int i=1; i < 5; i++ ){
Assertions.assertEquals(i,node.getKey());
node = node.getNext();
}
}
@Test
void removeTest(){
for(int i =3 ; i > 0 ; i--){
int result = listNodeStack.pop();
Assertions.assertEquals(i,result);
}
}
@Test
void removeFailTest(){
for(int i =3 ; i > 0 ; i--){
int result = listNodeStack.pop();
Assertions.assertEquals(i,result);
}
int result = listNodeStack.pop();
Assertions.assertEquals(-1,result);
}
}
package javaStudy.ListNodeStack;
public interface Stack {
boolean push(int data);
int pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment