🎁 코딩테스트/알고리즘
Stack, Queue Java로 구현하기(제일 간단한 array형식)
jhj.sharon
2023. 9. 13. 22:37
반응형
| Stack
public class Stack{
private static int MAX_STACK_SIZE = 10;
private int top;
private int[] data = new int[MAX_STACK_SIZE];
public Stack(){
top = -1;
}
public void push(int value){
if(isFull()){
System.out.println("stack이 가득 찼습니다.");
}else{
data[++top] = value;
}
}
public int pop(){
if(isEmpty()){
System.out.println("stack이 비어있습니다.");
}else{
return data[top--];
}
}
public int peek(){
if(isEmpty()){
System.out.println("stack이 비어있습니다.");
}else{
return data[top];
}
}
public boolean isFull(){
return top == MAX_STACK_SIZE -1;
}
public boolean isEmpty(){
return top == -1;
}
public int size(){
return top+1;
}
}
| Queue
public class Queue{
private int MAX_QUEUE_SIZE = 10;
private int front;
private int rear;
private int[] queue = new int [MAX_QUEUE_SIZE];
public Queue(){
front = -1;
rear = -1;
}
public void enqueue(int item){
if(queueisFull()){
System.out.println("Queue가 가득 차있습니다.");
}else{
queue[rear++] = item;
}
}
public int dequeue(){
if(queueisEmpty()){
System.out.println("Queue가 비어있습니다.");
return -1;
}else{
return queue[front++];
}
}
public int peek(){
if(queueisEmpty()){
System.out.println("Queue가 비어있습니다.");
return -1;
}else{
return queue[front];
}
}
public boolean queueisFull(){
return rear == MAX_QUEUE_SIZE-1;
}
public boolean queueisEmpty(){
return rear == front;
}
public int size(){
return rear - front +1 ;
}
}
반응형