Repository navigation
Expand file tree
/
Copy pathMyDeque.java
More file actions
122 lines (107 loc) · 3.27 KB
/
Copy pathMyDeque.java
File metadata and controls
122 lines (107 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package Deque;
public class MyDeque<E> {
private Object[] data;
private int size; // 배열의 최대 크기
private int front;
private int rear;
private int count; // 저장된 데이터 수
// 생성자1 (초기 용적 할당을 안할 경우)
public MyDeque(){
this.size = 1;
this.data = new Object[this.size];
this.count = 0;
this.front = 0;
this.rear = 0;
}
private void doubling(){
Object[] newData = new Object[this.size*2];
for(int i = 0; i< this.count; i++){
newData[i] = data[(this.front + i) % this.size];
}
this.data = newData;
this.front = 0;
this.rear = this.count;
this.size = this.size*2;
}
//데이터 추가(맨 앞에 삽입)
public void addFirst(E e){
if(this.count == this.size){
doubling();
}
this.front = (this.front-1+this.size)%this.size; // -1%5는 -1 -> 오류
this.data[this.front] = e;
this.count++;
}
//데이터 추가(덱 맨 뒤에 삽입)
public void addLast(E e){
if(this.count == this.size)
doubling();
this.data[this.rear] = e;
this.rear = (this.rear + 1) % this.size;
this.count ++;
}
//데이터 삭제( 맨 앞 삭제)
@SuppressWarnings("unchecked")
public E removeFirst() throws Exception{
if(isEmpty()){
throw new Exception("DequeUnderflow");
}
E removed = (E) this.data[this.front];
this.data[this.front] = null;
this.front = (this.front + 1) % this.size;
this.count --;
return removed;
}
//데이터 삭제(맨 뒤 삭제)
@SuppressWarnings("unchecked")
public E removeLast() throws Exception{
if(isEmpty()){
throw new Exception("DequeUnderflow");
}
this.rear = (this.rear-1+this.size) % this.size;
E removed = (E) this.data[this.rear];
this.data[this.rear] = null;
this.count--;
return removed;
}
//데이터 가져오기(맨 앞 데이터 가져오기(삭제 X))
@SuppressWarnings("unchecked")
public E peekFirst() throws Exception{
if(isEmpty()){
throw new Exception("DequeUnderflow");
}
return (E) this.data[this.front];
}
//데이터 가져오기(맨 뒤 데이터 가져오기(삭제 X))
@SuppressWarnings("unchecked")
public E peekLast() throws Exception{
if(isEmpty()){
throw new Exception("DequeUnderflow");
}
return (E) this.data[(this.rear-1 + this.size)%this.size];
}
public int size(){
return this.count;
}
public boolean isEmpty(){
return this.count == 0;
}
public boolean contains(E e){
for(int i = 0; i<count; i++){
if(this.data[(this.front + i) % this.size].equals(e))
return true;
}
return false;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder("[");
for(int i = 0; i<this.count; i++){
sb.append(this.data[(this.front + i) % this.size]);
if(i<this.count-1)
sb.append("-->");
}
sb.append("]");
return sb.toString();
}
}