スタック(STACK)
3681 ワード
スタックは、データを一時的に格納する資料構造の1つです.
スタック独自の特徴は、LIFOのデータ入出力メカニズムを備えており、上図に示すように、スタック形式でデータを入力して取り出すと、最後に入れたデータから順番に取り出すことができるということです.
スタックで最もよく使われる基本用語は、データ入力、データ出力、PEEKなどであり、スタックの最上位層をtop、最下位層をBOTTOMと呼ぶ.
このスタック構造もJAVAプログラム呼び出しや実行方法の際に用いられる構造である.
Recursionを迂回すると、StackServerFlowを喜んで迎えたことがありますが、誤った設計がBaseCaseに落ちず、自分自身を呼び出し続け、方法をスタックにプッシュし続けたため、ストレージしきい値を超えるとStackServerflowが発生します.
次に,JAVAコードを用いて配列を用いてスタックを実装する.
// 스택 클래스 구현하기
public class IntStack {
private int max; // 스택 용량
private int ptr; // 스택 포인터
private int[] stk; // 스택 본체
// 실행 시 예외 : 스택이 비어 있음
public class EmptyIntStackException extends RuntimeException{
public EmptyIntStackException(){};
}
// 실행 시 예외 : 스택이 가득 참
public class OverflowIntStackException extends RuntimeException{
public OverflowIntStackException(){};
}
public IntStack(int capacity){
ptr = 0;
max = capacity;
try {
stk = new int[max];
} catch (OutOfMemoryError e){ // 생성할 수 없음
max = 0;
}
}
public int push(int x) throws OverflowIntStackException{
if( ptr >= max )
throw new OverflowIntStackException();
return stk[ptr++] = x;
}
public int pop() throws EmptyStackException{
if( ptr <= 0)
throw new EmptyStackException();
return stk[--ptr];
}
public int peek() throws EmptyStackException{
if ( ptr <= 0 )
throw new EmptyStackException();
return stk[ptr -1];
}
public int indexOf(int x){ // x 값에 해당하는 스택의 index 반환 없다면 -1
for (int i = ptr -1; i >= 0 ; i--){
if(x == stk[ptr])
return i;
}
return -1;
}
public void clear(){ // 스택 비우기
ptr = 0;
}
public int capacity(){ // 스택의 한계 용량치
return max;
}
public int size(){ // 스택의 크기(데이터가 몇개 들어있는지)
return ptr;
}
public boolean isFull(){ // 스택이 한계 용량치 인지 확인
return ptr >= max;
}
public void dump(){ // 스택을 bottom 부터 top 까지 scan
if( ptr <= 0 ){
System.out.println("스택이 비어 있습니다.");
}
else {
for(int i = 0; i < ptr; i++)
System.out.print(stk[i] + " ");
System.out.println();
}
}
}
次に、intタイプではなくGenericを使用してスタックを実装します.public class GenStack<T> {
private int max;
private int ptr;
private T[] stk;
public static class EmptyStackException extends RuntimeException{
public EmptyStackException(){}
}
public static class OverflowStackException extends RuntimeException {
public OverflowStackException() {}
}
public GenStack(int max) {
this.max = max;
ptr = 0;
stk = (T[])new Object[max];
}
public T push (T value) throws OverflowStackException{
if(ptr >= max)
throw new OverflowStackException();
return stk[ptr++] = value;
}
public T pop() throws EmptyStackException{
if(ptr <= 0)
throw new EmptyStackException();
return stk[--ptr];
}
public T peek() throws EmptyStackException{
if(ptr <= 0 )
throw new EmptyStackException();
return stk[ptr-1];
}
Reference
この問題について(スタック(STACK)), 我々は、より多くの情報をここで見つけました https://velog.io/@jaden_94/스택STACKテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol