티스토리 뷰

반응형

 

 

해커랭크 Day 18 챌린지를 시작해보자. 😆

 

오늘은 Stack과 Queue에 대해 배웠다.

 

Stack과 Queue에 대해서 잘 모르는 독자는

다음의 링크를 참고하길 바란다.

(글자 클릭 시 이동)

 

[자바의 정석] Ch11-15 스택과 큐(Stack & Queue)란?

🤔 Stack이란? ✔ LIFO 구조(Last In First Out) 마지막에 저장된 것을 제일 먼저 꺼냄. 저장(push) 추출(pop) 🤔 Queue란? ✔ FIFO 구조(First In First Out) 제일 먼저 저장한 것을 제일 먼저 꺼냄. 🤔 Stack의..

dandev.tistory.com

 

 

필자의 '자바의 정석' 포스팅인데

저 글을 읽고도 이해가 되지 않는다면

해당하는 '자바의 정석' 강의를 듣고 문제를 푸는 것을 추천한다!!

 

 

그럼 이제 강의 소스부터 확인해보자.

 


 


import java.util.*;

/*
traversing data structures
- The only way to traverse a stack or a queue is to pop / dequeue --> which means we remove everything in the given stack or queue
- that means the data is gone unless we save it in a variable
- note this is not the case for linked lists
- of the linked list so that it can act like a queue or a stack --> with the appropriate behavior
 */
public class Queuey {
    LinkedList queue;

    // Making a queue instance
    public Queuey() {
        queue = new LinkedList();
    }

    // Is our queue empty?
    public boolean isEmpty() {
        return queue.isEmpty();
    }

    // What is the size of our queue?
    public int size() {
        return queue.size();
    }

    // Enqueuing an item
    public void enqueue(String n) {
        queue.addLast(n);
    }

    // Dequeuing an item
    public String dequeue() {
        return (String) queue.remove(0);
    }

    // Peek at the first item
    public String peek() {
        return (String) queue.get(0);
    }

    public static void main(String[] args) {
        Stack<String> stacky = new Stack<>();
        stacky.push("there");
        stacky.push("hi");
        System.out.print(stacky.pop() + " ");
        System.out.println("Peek: " + stacky.peek());
        System.out.println(stacky.pop() + "!");
        System.out.println("Size: " + stacky.size());


//        Queuey stringQueue = new Queuey();
//        stringQueue.enqueue("hi");
//        stringQueue.enqueue("there");
//        System.out.print(stringQueue.dequeue() + " ");
//        System.out.print(stringQueue.dequeue() + " ");

//        Queuey numberQueue = new Queuey();
//        numberQueue.enqueue(5);
//        numberQueue.enqueue(7);
//        numberQueue.enqueue(6);
//        System.out.println("First out: " + numberQueue.dequeue());
//        System.out.println("Peek at second item: " + numberQueue.peek());
//        System.out.println("Second out: " + numberQueue.dequeue());
//        System.out.println("Third out: " + numberQueue.dequeue());

    }
}

 

 

queue() 에서는 queue를 생성하고

isEmpty()에서는 queue가 비었는지 체크하고

size() 메서드에서는 queue의 사이즈를 반환한다.

 

enqueue() 메서드에서는 매개변수로 받은 String n을

queue의 마지막에 넣고

 

dequeue() 메서드에서는

인덱스 0번째의 값을 제거한다.

 

peek() 메서드는 첫 번째에 있는 값을 return한다.

 

 

linkedList와 Stack, Queue의 개념에 대해 

잘 알고있어야 코드를 이해할 수 있으므로

필자가 위에 추천한 링크를 학습하기를 추천한다.

 

 


 

그럼 다음 포스팅에서 다시 만나자. 😊

반응형