C# 으로 구현한 Deque (덱)
Data structure 2020. 11. 19. 00:25반응형
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Deque
{
//https://www.programiz.com/dsa/deque
public class Deque
{
static int MAX = 100;
int[] arr;
int front;
int rear;
int size;
public Deque(int size) {
this.arr = new int[MAX];
front = -1;
rear = 0;
this.size = size;
}
public bool IsFull() {
return ((this.front == 0 && rear == size - 1) || this.front == rear + 1);
}
public bool IsEmpty() {
return (front == -1);
}
public void InsertFront(int val) {
if (this.IsFull()) {
Console.WriteLine("Full");
return;
}
if (this.front == -1)
{
this.front = 0;
this.rear = 0;
}
else if (this.front == 0)
{
this.front = this.size - 1;
}
else {
this.front = this.front - 1;
}
this.arr[this.front] = val;
}
public void InsertRear(int val) {
if (this.IsFull()) {
Console.WriteLine("Full");
return;
}
if (this.front == -1)
{
this.front = 0;
this.rear = 0;
}
else if (this.rear == this.size - 1)
{
this.rear = 0;
}
else {
this.rear = this.rear + 1;
}
this.arr[this.rear] = val;
}
public void DeleteFront() {
if (this.IsEmpty()) {
Console.WriteLine("Empty");
return;
}
if (this.front == this.rear)
{
this.front = -1;
this.rear = -1;
}
else if (this.front == this.size - 1)
{
this.front = 0;
}
else {
this.front = this.front + 1;
}
}
public void DeleteRear() {
if (this.IsEmpty()) {
Console.WriteLine("Empty");
return;
}
if (this.front == this.rear)
{
this.front = -1;
this.rear = -1;
}
else if (this.rear == 0)
{
this.rear = this.size - 1;
}
else {
this.rear = this.rear - 1;
}
}
public int GetFront() {
if (this.IsEmpty()) {
throw new Exception("empty");
}
return this.arr[this.front];
}
public int GetRear() {
if (this.IsEmpty())
{
throw new Exception("empty");
}
return this.arr[this.rear];
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Deque
{
class Program
{
static void Main(string[] args)
{
var dq = new Deque(4);
dq.InsertRear(12);
dq.InsertRear(14);
Console.WriteLine("{0}", dq.GetRear()); //14
dq.DeleteRear();
Console.WriteLine("{0}", dq.GetRear()); //12
dq.InsertFront(13);
Console.WriteLine("{0}", dq.GetFront()); //13
dq.DeleteFront();
Console.WriteLine("{0}", dq.GetFront()); //12
}
}
}
반응형
'Data structure' 카테고리의 다른 글
배열로 구현한 Stack in C# (0) | 2020.10.23 |
---|---|
단일연결리스트 (SinglyLinkedList) in c# (0) | 2020.10.23 |
Binary Search Tree (0) | 2020.05.29 |
이진 트리 (0) | 2019.08.14 |
이진 탐색 (Binary Search) (0) | 2019.08.14 |