[JAVA] Stack과 Queue, Dequeue

mango·2023년 6월 25일
0

JAVA

목록 보기
6/10

import java.util.*;

코드 맨 위에 패키지 항상 임포트 해주고 시작

🍦 Stack

  • Stack은 FILO first in Last out 규칙을 가지는 자료구조이며, 자바에서 클래스로 제공을 하고 있음
Stack<Integer> myStack = new Stack<Integer>();

myStack.push(5);
myStack.push(3);
myStack.push(1);

while(!myStack.empty()){
	System.out.println(myStack.pop());
}

- Stack의 함수 모아보기

- Stack.push(o)
- Stack.add(o)		//= 동일

- Stack.pop()		//삭제하고 반환. 비어있으면   EmptyStackException 발생
- Stack.peek()		//삭제 없이 반환. 비어있으면   EmptyStackException 발생

- Stack.empty()		// 비었는지 여부 반환
- Stack.isEmpty()	// = 동일

- Stack.size()		//스택 사이즈 반환
- Stack.search(o)	//스택에서 o를 찾아서 위치를 반환함(0이 아닌 1부터 시작함)

0. 선언

Stack<Integer> myStack = new Stack<Integer>();

1. 삽입

myStack.push(4);		
- add도 있지만 Stack이란 것을 구별해주는 push 사용하기

myStack.add(4);		
- push와 동일, Collection의 함수

2. 제거

myStack.pop();	

Integer result = myStack.pop();		
- Last In값 삭제하고 반환. 비어있으면 EmptyStackException 발생

Integer result = myStack.peek();	
- Last In값 삭제 없이 반환. 비어있으면 EmptyStackException 발생

3. 조회

int where = myStack.search(4);
- 스택에서 4라는 값을 찾아서 위치를 반환함
  ※ 0이 아닌 1부터 시작하는 것 주의!!!

4. 그 외

boolean isEmpty = myStack.empty()		
- 비었는지 여부 반환

boolean isEmpty = myStack.isEmpty()	
- 비었는지 여부 반환

int stackSize = myStack.size()		
- 스택 사이즈 반환





🍦 Queue

  • Queue은 FIFO first in First out 규칙을 가지는 자료구조이며, 자바에서 클래스로 제공을 하지 않지만 Interface를 제공해 LinkedList 형태로 사용할 수 있음
Queue<Integer> myQueue = new LinkedList<>();

myQueue.add(5);
myQueue.add(3);
myQueue.add(1);

while(!myQueue.isEmpty()){
	System.out.println(myQueue.poll());
}

- Queue의 함수 모아보기

- Queue.add(o)		
- Queue.offer(o)	//=동일

- Queue.poll()		//First In 값 삭제 하고 반환. 비어있으면 null 반환
- Queue.peek()		//First In 값 삭제 없이 반환. 비어있으면 null 반환
- Queue.element()	//First In 값 삭제 없이 반환. 비어있으면 NoSuchElementException 발생

- Queue.isEmpty()

0. 선언

자바에서 큐는 LinkedList로 선언한다.

Queue<Integer> myQueue = new LinkedList<>();

1. 삽입

myQueue.offer(5);
- Rear에 값 삽입
- 삽입 성공시 true 반환
- 큐가 가득찬 경우 false 반환


myQueue.add(5);
- Rear에 값 삽입
- 삽입 성공시 true 반환
- 큐가 가득찬 경우 Exception 발생

2. Front값 반환

myQueue.peek()		
- Front값 반환
- 비어있으면 null 반환


myQueue.element();
- Front 값 반환
- 비어있으면 Exception 발생

3. 삭제

myQueue.poll()		
- Front값 삭제 후 반환
- 비어있으면 null 반환


myQueue.remove();	
- Front값 삭제 후 반환
- 비어있으면 Exception 발생


boolean isRemoved = myQueue.remove(5);	
- 큐에서 5 값을 찾아서 삭제
- 성공시 true, 없을시 false


myQueue.clear()
- 큐 비우기

4. 조회

boolean isExist = myQueue.contains(5);
- 5라는 값이 존재하는지 여부 반환

int index = myQueue.indexOf(5);
- 5라는 값을 Front 부터 검색해서 index 반환

int index = myQueue.lastIndexOf(5);
- 5라는 값을 Rear 부터 검색해서 index 반환

5. 그 외

boolean isEmpty = myQueue.isEmpty();
- 큐가 비었는지 여부 반환


int queueSize = myQueue.size();	
- 큐 사이즈 반환



★ 정리하자면, 해당 실행이 실패했을 때 ★

1. Exception을 발생시키지 않는 함수

myQueue.offer(3);	실패시 false
myQueue.peek();		비었을시 null	
myQueue.poll();		없을시 null

2. Exception을 발생시키는 함수

myQueue.add(3);		실패시 Exception
myQueue.element();	비었을시 Exception
myQueue.remove();	비었을시 Exception

-> offer, peek, poll 예외발생 X






🍦 Dequeue

큐인데, Front만 제거하고 Rear에만 넣을 수 있는 것이 아니라
Front 삽입 제거, Rear 삽입 제거 모두 가능한 자료구조

Dequeue<Integer> myDequeue = new LinkedList<>();

// 값 추가
myDequeue.addFirst(5);	
myDequeue.addLast(3);

//값 조회
myDequeue.getFirst();	
myDequeue.getLast();

//front, rear값 반환 = 조회
myDequeue.peekFirst();	
myDequeue.peekLast();

//front, rear 반환후 삭제
myDequeue.pollFirst();	
myDequeue.pollLast();






🍦 PriorityQueue

0. 선언

1. 최소힙(오름차순)
PriorityQueue<Integer> myPQ = new PriorityQueue<Integer>(); 
- 낮은 숫자부터 peek

2. 최대힙(내림차순)
PriorityQueue<Integer> myPQ = new PriorityQueue<Integer>(Collections.reverseOrder());
- 높은 숫자부터 peek

1. 삽입

myPQ.offer(4);		
- Queue의 공간이 가득차 삽입 실패하면 false

myPQ.add(4);		
- Queue의 공간이 가득차 삽입 실패하면 Exception 발생

2. Front값 반환

myPQ.peek()		
- Front값 반환
- 비어있으면 null 반환


myPQ.element();
- Front 값 반환
- 비어있으면 Exception 발생

3. 삭제

myPQ.poll()		
- Front값 삭제 후 반환
- 비어있으면 null 반환


myPQ.remove();	
- Front값 삭제 후 반환
- 비어있으면 Exception 발생


boolean isRemoved = myPQ.remove(5);	
- 큐에서 5 값을 찾아서 삭제
- 성공시 true, 없을시 false


myPQ.clear()
- 큐 비우기

4. 조회

boolean isExist = myPQ.contains(5);
- 5라는 값이 존재하는지 여부 반환

5. 그 외

boolean isEmpty = myQueue.isEmpty();
- 큐가 비었는지 여부 반환


int queueSize = myQueue.size();	
- 큐 사이즈 반환

6. 예제

  • Student 클래스를 데이터형태로 하는 PriorityQueue 선언
  • 우선순위 기준은 Comparator를 implements하는 StudentComparator를 선언해서 만들어줌
import java.util.Comparator;
import java.util.PriorityQueue;
 
class Student {
    int mathScore; // 수학점수
    int engScore;  // 영어점수
 
    public Student(int mathScore, int engScore){
        this.mathScore = mathScore;
        this.engScore = engScore;
    }
}
// 클래스 객체의 우선순위를 위한 클래스
class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.mathScore == o2.mathScore) {
            return o2.engScore - o1.engScore;
        } else {
            return o1.mathScore - o2.mathScore;
        }
    }
}
 
public class Example {
 
    public static void main(String[] args) {
 
        // 클래스 객체에 대한 우선순위 기준 제공
        PriorityQueue<Student> pQ = new PriorityQueue<>(1, new StudentComparator());
 
        pQ.offer(new Student(70, 50));  // 우선순위 큐에 클래스 객체를 추가
        pQ.offer(new Student(60, 50));  // 우선순위 큐에 클래스 객체를 추가
        pQ.offer(new Student(70, 40));  // 우선순위 큐에 클래스 객체를 추가
 
        while (!pQ.isEmpty()) {
            Student s = pQ.poll();
            System.out.printf("Student\'s MathScore and engScore: %d, %d \n", s.mathScore, s.engScore);
        }
    }
}

profile
앎의 즐거움을 아는 나는 mango ♪

0개의 댓글