wiki/큐(자료구조).md

86 lines
16 KiB
Markdown
Raw Permalink Normal View History

2023-02-12 03:02:55 +09:00
---
title: 큐(Queue)
description: 자료 구조 큐
published: true
date: 2020-09-22T08:12:23.058Z
tags: 컴퓨터
editor: markdown
dateCreated: 2020-09-22T07:25:17.866Z
---
# 큐(Queue)
FIFO(first in, first out)
```rust
trait Queue<T>{
fn enqueue(&mut self,e: T) -> Result<()>;
fn dequeue(&mut self) -> Result<T>;
fn is_empty() -> bool;
fn peek(&mut self) -> Result<&mut T>;
fn size(&self) -> usize;
}
```
## 선형큐(linear queue)
```diagram
PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzMjFweCIgaGVpZ2h0PSIxNTFweCIgdmlld0JveD0iLTAuNSAtMC41IDMyMSAxNTEiIGNvbnRlbnQ9IiZsdDtteGZpbGUgaG9zdD0mcXVvdDtlbWJlZC5kaWFncmFtcy5uZXQmcXVvdDsgbW9kaWZpZWQ9JnF1b3Q7MjAyMC0wOS0yMlQwNzozNjo1OS41MTlaJnF1b3Q7IGFnZW50PSZxdW90OzUuMCAoV2luZG93cykmcXVvdDsgdmVyc2lvbj0mcXVvdDsxMy43LjMmcXVvdDsgZXRhZz0mcXVvdDtoeEhELTE3WVY2ZktkNklYSmoyQyZxdW90OyB0eXBlPSZxdW90O2VtYmVkJnF1b3Q7Jmd0OyZsdDtkaWFncmFtIGlkPSZxdW90O09LRUdfVjE4cld2NVFBSW5zaGt5JnF1b3Q7IG5hbWU9JnF1b3Q7UGFnZS0xJnF1b3Q7Jmd0OzNWZkxqdE13RlAyYUxFRjVOZE5aOWpFREd5UkVGOERTaW04VEN5Y09qdE9tZkQzWHRkMDhDeU1RbldHa1NyV1A3V3VmYzV4N0V5L2FGTzA3U2FyOGc2REF2ZENuclJkdHZUQU00akQw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5lLWhlaWdodDogMS4yOyBwb2ludGVyLWV2ZW50czogYWxsOyB3aGl0ZS1zcGFjZTogbm9ybWFsOyB
```
### 구현
```rust
const QUEUE_SIZE=128;
struct CircularQueue<T>{
arr:[T;QUEUE_SIZE],
first: u32,
near : u32
};
```
isfull
```rust
impl CircularQueue<T>{
fn new() -> CircularQueue<T>{
CircularQueue<T>{
[0;QUEUE_SIZE]
}
}
fn is_full(&self) -> bool{
(self.rear + 1) % QUEUE_SIZE == self.first;
}
}
```
```rust
impl Queue<T> for CircularQueue<T>
{
fn is_empty(&self){
self.near == self.first
}
fn enqueue(&mut self, item: T) -> Result<()>{
if self.is_full(){
Error()
}
else{
self.rear = (self.rear +1) % QUEUE_SIZE;
self.arr[self.rear + 1] = item;
Ok(())
}
}
fn dequeue(&mut self) -> Result<T>{
if self.is_empty(){
Error()
}
else{
self.first = (self.first + 1) % QUEUE_SIZE;
Ok(self.arr[self.rear])
}
}
}
```