프로그래밍/JAVA

Implement Stack

DevIt 2016. 12. 1. 23:44



- LIFO(Last In First Out)

- top은 마지막에 들어온 element를 가르킴


interface Stack{

boolean isEmpty();

boolean isFull();

void push(char item);

char pop();

}


class ArrayStack implements Stack{

private int top;

private int size;

private char[] arr;

public ArrayStack(int size){

this.size = size;

arr = new char[this.size];

top = -1;

}

@Override

public boolean isEmpty(){

if(this.top == -1){

return true;

}

return false;

}

@Override

public boolean isFull(){

if(this.size-1 <= this.top){

return true;

}

return false;

}


@Override

public void push(char element) {

if(!isFull()){

System.out.println("push()");

arr[++this.top] = element;

}else{

System.out.println("[push()] It's full.");

}

}


@Override

public char pop() {

if(!isEmpty()){

System.out.println("pop()");

return arr[this.top--];

}

System.out.println("[pop()] It's empty.");

return 0;

}

public void printStack(){

if(isEmpty()){

System.out.println("[printStack()] It's empty.\n");

}else{

System.out.print("arr >> ");

for(int i=0; i<=this.top; i++){

System.out.print(this.arr[i] + " ");

}

System.out.println("\n");

}

}

}


public class dailyCode{

public static void main(String[] args){

final int MAX_STACK_SIZE = 5;

ArrayStack stack = new ArrayStack(MAX_STACK_SIZE);

stack.pop();

stack.printStack();

stack.push('A');

stack.printStack();

stack.push('B');

stack.printStack();

stack.push('C');

stack.printStack();

stack.push('D');

stack.printStack();

stack.push('E');

stack.printStack();

stack.push('F');

stack.printStack();

stack.pop();

stack.printStack();

stack.push('F');

stack.printStack();

}