SSAFY/Data Structure

Stack

믕비 2023. 5. 5. 17:15

https://swexpertacademy.com/main/code/referenceCode/referenceCodeDetail.do?referenceId=AVuoqWnqAADw5fUK&category=undefined 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

필요한 스택메소드들을 직접 구현해서 사용하는 코드였다.

배열을 사용해서 필요한 공간만 stack으로 사용할 수 있기 때문에 메모리 사용에 있어서는 더 효율적인 것 같다.

Integer와 int의 차이를 다시 상기시킬 수 있었다.

 

[코드]

package DataStructure;

import java.io.IOException;
import java.util.Scanner;

public class DS_Stack {
	
	static final int MAX_N = 100;
	
	static int top;
	static int stack[] = new int[MAX_N];
	
	static void stackInit() {
		top = 0;
	}
	
	static boolean stackIsEmpty() {
		return (top == 0);
	}
	
	static boolean stackIsFull() {
		return (top == MAX_N);
	}
	
	static boolean stackPush(int value) {
		if(stackIsFull()) {
			System.out.println("stack overflow ! ");
			return false;
		}
		stack[top] = value;
		top++;
		
		return true;
	}
	// null 값 처리 위해서 Integer 사용
	static Integer stackPop() {
		if(top == 0) {
			System.out.println("stack is empty ! ");
			return null;
		}
		
		top--;
		Integer value = new Integer(stack[top]);
		
		return value;
	}
	
	public static void main(String[] args) throws IOException{
		Scanner sc = new Scanner(System.in);
		
		int T = sc.nextInt();
		
		for(int t = 1; t <= T; t++) {
			int N = sc.nextInt();
			
			stackInit();
			for(int i = 0; i < N; i++) {
				int value = sc.nextInt();
				stackPush(value);
			}
			
			System.out.print('#' + t + ' ');
			
			while(!stackIsEmpty()) {
				Integer value = stackPop();
				if(value != null) {
					//Integer를 int로 변환해줘야 값 출력 가능
					System.out.print(value.intValue() + ' ');
				}
			}
			System.out.println();
		}
		sc.close();
	}

}

'SSAFY > Data Structure' 카테고리의 다른 글

Tree  (0) 2023.05.06
Hash  (0) 2023.05.06
PriorityQueue  (1) 2023.05.06
Queue  (0) 2023.05.06