자료구조와 알고리듬 With Java/[Study] BAEKJOON 프로그래머스 CodeUp LeetCode

Java로 Stack 구현하기

계란💕 2022. 3. 11. 23:17

 

  Ex) 

<hide/>
interface IStackable0{
	boolean empty();
	int peek();
	void pop();
	void push(int nData);
	// int search(int nData);
}
public class StackPractice implements IStackable0{
	private int [] mnArray;
	private int mnCapacity;
	private int mnTop;
	
	public StackPractice(int nCapacity) {
		mnArray = new int[nCapacity];
		mnCapacity = nCapacity;
		mnTop = 0;
	}
	public boolean empty() {
		return (0 == mnTop);
	}
	public void push(int nData) {
		if( true == full()) {
			System.out.println("Stack Overflow!");
			return;
		}
		mnArray[mnTop++] = nData;
	}
	public void pop(){
		if( true == empty()) {
			System.out.println("Stack Underflow!");
			return;
		}
		--mnTop;
	}
	public int peek() {
		if(true == empty()) {
			System.out.println("Stack Underflow!");
			return -1;
		}
		return mnArray[mnTop-1];
	}
	public boolean full() {
		return (mnCapacity == mnTop);
	}
	public void print() {
		System.out.printf("======\n");
		System.out.printf("Stack Capacity: %d\n", mnCapacity);
		System.out.printf("Stack Size: %d\n", mnTop);
		System.out.printf("Stack elements: ");
		for(int i = 0; i < mnTop; ++i)
		{
			System.out.printf("%d ", mnArray[i]);
		}	
		System.out.printf("\n");
		System.out.printf("=========\n");
	}
	public static void main(String[] args) {
		int nCapacity = 5;
		StackPractice st = new StackPractice(nCapacity);
	
		st.print();
		st.push(10);
		st.push(20);
		st.push(30);
		st.print();
		
		while(false == st.empty()) {
			System.out.printf("%d ", st.peek());
			st.pop();
		}
		System.out.println();
		st.print();
	}
}

  Note) 실행 결과

 

  - pop(), peek(), empty(), full(), push()를 구현한다.

  - stack의 특성에 따라서 배열에 저장된 값 중 가장 위의 값을 먼저 출력(FIFO)하는 구조로 만든다.