๊ด€๋ฆฌ ๋ฉ”๋‰ด

Coding Planet

Stack, Queue Java๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ(์ œ์ผ ๊ฐ„๋‹จํ•œ arrayํ˜•์‹) ๋ณธ๋ฌธ

๐ŸŽ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ/์•Œ๊ณ ๋ฆฌ์ฆ˜

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 ;
    }
}
๋ฐ˜์‘ํ˜•
Comments