Stack and Queue ๊ตฌํ˜„ ๐Ÿ“Œ

imsยท2021๋…„ 6์›” 4์ผ
0

NEW ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
11/14

๐Ÿ“Œ Stack

๐Ÿ”ฅ using array

import java.util.NoSuchElementException;

public class StackImpl {
    static final int STACK_SIZE = 3;
    int size=STACK_SIZE;
    // ๋‹ค์Œ์— ๋“ค์–ด๊ฐˆ ๊ฐ’์„ ๊ฐ€๋ฅดํ‚ด
    int index=0;
    int[] arr = new int[STACK_SIZE];

    void push(int val){
        if(isStackOverSize()){
            extendStackSize();
        }
        arr[index++]=val;
    }

    int pop(){
       if (index==0){
           throw new NoSuchElementException();
       }
       // index๊ฐ€ ๋‹ค์Œ์— ๋“ค์–ด๊ฐˆ ๊ฐ’์„ ๊ฐ€๋ฅดํ‚ค๊ธฐ ๋•Œ๋ฌธ์— ๋ฏธ๋ฆฌ ๋นผ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
       return arr[--index];
    }

    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i=0;i<index;i++){
            sb.append(arr[i]);
            if(i!=index-1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    boolean isStackOverSize(){
        return index >= size;
    }
    void extendStackSize(){
        int[] temp = arr;
        size = index*STACK_SIZE;
        arr = new int[size];
        for(int i=0;i<index;i++){
            arr[i] = temp[i];
        }
    }
}

๐Ÿ“Œ Queue

๐Ÿ”ฅ using node

import java.util.NoSuchElementException;

public class QueueImpl {
    class Node{
        int val;
        Node next;
        Node(int val){
            this.val=val;
        }
    }

    Node first;
    Node last;

    void offer(int val){
        Node node = new Node(val);
        if(last!=null){
            last.next=node;
        }
        last = node;
        // ์ฒซ๋ฒˆ์งธ ๊ฐ’์„ ๋„ฃ์—ˆ์„ ๋•Œ first = null ์ž„ ๊ทธ๋ž˜์„œ first = last ์‹œ์ผœ์ค˜์•ผ ํ•œ๋‹ค
        if(first==null){
            first=last;
        }
    }

    int poll(){
        if (first==null){
            throw new NoSuchElementException();
        }
        int returnValue = first.val;
        first= first.next;
        // last์— ๋Œ€ํ•œ ์„ค์ •๊ฐ’๋„ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.
        if(first==null){
            last=null;
        }
        return returnValue;
    }

    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node node = this.first;
        while(node!=null){
            sb.append(node.val);
            if(node.next!=null){
                sb.append(",");
            }
            node=node.next;
        }
        sb.append("]");
        return sb.toString();
    }
}
profile
ํ‹ฐ์Šคํ† ๋ฆฌ๋กœ ์ด์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค! https://imsfromseoul.tistory.com/ + https://camel-man-ims.tistory.com/

0๊ฐœ์˜ ๋Œ“๊ธ€