95 lines
2.9 KiB
Java
95 lines
2.9 KiB
Java
import java.util.*;
|
|
|
|
class Stack{
|
|
private int[] data;
|
|
private int top;
|
|
private int maxSize;
|
|
|
|
Stack(int maxSize){
|
|
data = new int[maxSize];
|
|
top = -1;
|
|
this.maxSize = maxSize;
|
|
}
|
|
|
|
void stackInfo(){
|
|
if(top == -1){
|
|
System.out.println("현재 스택 목록 : Empty!");
|
|
return;
|
|
}
|
|
System.out.printf("현재 스택 목록 : ");
|
|
for(int i=0; i<=top; i++) {
|
|
System.out.printf("%d ",this.data[i]);
|
|
}
|
|
System.out.printf("\ntop : %d\n",this.top);
|
|
}
|
|
|
|
void push(int value){
|
|
if(top == maxSize - 1){
|
|
System.out.println("스택이 꽉찼기 때문에 추가할 수 없습니다.");
|
|
return;
|
|
}
|
|
this.data[++(this.top)] = value;
|
|
}
|
|
|
|
void pop(){
|
|
if(this.top == -1){
|
|
System.out.println("스택이 비어있어서 처리할 수 없습니다.");
|
|
return;
|
|
}
|
|
System.out.printf("빠져나온 데이터 : %d\n",this.data[(this.top)--]);
|
|
}
|
|
|
|
int peek(){
|
|
return this.data[top];
|
|
}
|
|
}
|
|
|
|
public class DS_stack {
|
|
public static void main(String[] args) {
|
|
Scanner Order = new Scanner(System.in);
|
|
System.out.printf("스택의 최대길이를 입력해주세요. : ");
|
|
int maxSize = Integer.parseInt(Order.nextLine());
|
|
Stack stack = new Stack(maxSize);
|
|
boolean exit = false;
|
|
|
|
while(!exit){
|
|
System.out.println("======명령어 목록======");
|
|
System.out.println("1. push <value>");
|
|
System.out.println("2. pop");
|
|
System.out.println("3. peek");
|
|
System.out.println("4. info");
|
|
System.out.println("5. exit");
|
|
System.out.println("=====================");
|
|
System.out.printf("명령어를 입력하세요 : ");
|
|
String[] order = Order.nextLine().split(" ");
|
|
if (order[0] != null){
|
|
switch (order[0]){
|
|
case "push":
|
|
stack.push(Integer.parseInt(order[1]));
|
|
break;
|
|
case "pop":
|
|
stack.pop();
|
|
break;
|
|
case "peek":
|
|
System.out.printf("최상단 값 : %d\n",stack.peek());
|
|
break;
|
|
case "info":
|
|
stack.stackInfo();
|
|
break;
|
|
case "exit":
|
|
exit = true;
|
|
System.out.println("종료합니다!");
|
|
break;
|
|
default:
|
|
System.out.println("제대로 입력해주세요.");
|
|
break;
|
|
}
|
|
}
|
|
else{
|
|
System.out.println("명령어 목록을 잘 확인해서 다시 입력해주세요.");
|
|
}
|
|
}
|
|
Order.close();
|
|
}
|
|
}
|