[Java 자료구조] 스택 구현해보기

2022. 2. 7. 16:52·Java & Kotlin

스택(Stack) 구현해보기

배열을 구현한 MyArray 클래스를 이용하여 스택을 구현해본다. 스택의 연산에는 top에 자료를 삽입하는 push(), top-1의 자료를 반환하여 제거하는 pop(), 값을 반환만 해주는 peek() 메서드가 있다.

 

MyArrayStack.java
  • 연결 리스트는 메모리를 그때그때 할당받기 때문에 꽉 찼는지 여부를 확인해주지 않아도 되지만 배열은 체크해주어야 한다.
package ch04;

import ch02.MyArray;

public class MyArrayStack {
	
	MyArray arrayStack;
	int top;
	
	public MyArrayStack() {
		top = 0;
		arrayStack = new MyArray();
	}
	
	public MyArrayStack(int size) {
		top = 0;
		arrayStack = new MyArray(size);
	}
	
	public void push(int data) {
		if(isfull()) {	// 스택이 꽉 찼으면 에러메세지 출력
			System.out.println("Stack is full");
			return;
		}
		arrayStack.addElement(data);
		top++;
	}
	
	public int pop() {
		if( isEmpty() ) {	// 스택이 비었으면 에러 메세지 출력 
			System.out.println("Error");
			return MyArray.ERROR_NUM;
		}
		
		return arrayStack.removeElement(--top);	// top-1 번째 요소 반환하고 제거
	}
	
	public int peek() {
		if( isEmpty() ) {
			System.out.println("Error");
			return MyArray.ERROR_NUM;
		}
		
		return arrayStack.getElement(top-1); // top-1 번째 요소 반환만
	}
	
	public boolean isfull() {
		if(top == arrayStack.ARRAY_SIZE) {
			return true;
		}
		else return false;
	}
	
	public boolean isEmpty() {
		if(top == 0) {
			return true;
		}
		else return false;
	}
	
	public void printAll() {
		arrayStack.printAll();
	}
}

 

MyArrayStackTest.java
package ch04;

public class MyArrayStackTest {

	public static void main(String[] args) {
		
		MyArrayStack stack = new MyArrayStack(3);
		stack.push(10);
		stack.push(20);
		stack.push(30);
		stack.push(40);	// 실행되지 않음
		stack.printAll();
		
		System.out.println("==================");
		
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.peek());
		
	}

}

 

 

수행 결과
Stack is full
10
20
30
==================
30
20
10
저작자표시 비영리 변경금지 (새창열림)

'Java & Kotlin' 카테고리의 다른 글

[Java 자료구조] 큐 구현해보기  (0) 2022.02.07
[Java 자료구조] 연결 리스트 구현해보기  (0) 2022.02.07
[Java 자료구조] 배열 구현해보기  (0) 2022.02.07
'Java & Kotlin' 카테고리의 다른 글
  • [Java 자료구조] 제네릭 프로그래밍
  • [Java 자료구조] 큐 구현해보기
  • [Java 자료구조] 연결 리스트 구현해보기
  • [Java 자료구조] 배열 구현해보기
Sue
Sue
개발 공부 로그
  • Sue
    Sue's devlog
    Sue
  • 전체
    오늘
    어제
    • 분류 전체보기 (122)
      • Algorithm (2)
      • WEB (8)
      • Java & Kotlin (83)
      • Spring (26)
      • Database (1)
      • Infra (0)
      • Git (1)
      • devlog (1)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Sue
[Java 자료구조] 스택 구현해보기
상단으로

티스토리툴바