본문 바로가기
프로그래밍 언어/자료구조

4.스택(Stack) 구현

by lroot 2022. 5. 27.
728x90
반응형

Stack의 특징

- 맨 마지막 위치(top)에서만 자료를 추가, 삭제, 꺼내올 수 있음(중간의 자료를 꺼낼 수 없음)

- Last In First Out (후입선출) 구조

- 택배 상자가 쌓여있는 모양

- 가장 최근의 자료를 찾아오거나 게임에서 히스토리를 유지하고 이를 무를때 사용할 수 있음

- 함수의 메모리는 호출 순서에 따른 stack 구조

- jdk 클래스 : Stack

 

배열을 활용한 stack 구현

- MyArrayStack.java

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("stack is empty");
return MyArray.ERROR_NUM;
}

return arrayStack.removeElement(--top);
}

public int peek() {

if(isEmpty()) {
System.out.println("stack is empty");
return MyArray.ERROR_NUM;
}

return arrayStack.getElement(--top);
}


public boolean isFull() {

if(top == arrayStack.ARRAY_SIZE) {
return true;
}
else return false;
}

public boolean isEmpty() {
if(top == 0) {
System.out.println("stack is empty");
return true;
}
else return false;
}

public void printAll {
arrayStack.printAll();
}


}

'프로그래밍 언어 > 자료구조' 카테고리의 다른 글

5.큐(Queue) 구현  (0) 2022.05.27
3.연결 리스트(LinkedList)구현  (0) 2022.05.27
2.배열(Array) 구현  (0) 2022.05.27
1.여러가지 자료구조(선형/비선형)  (0) 2022.05.26

댓글