-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntStack.java
More file actions
97 lines (84 loc) · 2.36 KB
/
IntStack.java
File metadata and controls
97 lines (84 loc) · 2.36 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
package stack_queue;
// int형 스택 구현
public class IntStack {
private int max; // 스택 용량
private int ptr; // 스택 포인터
private int[] stk; // 스택 본체
// 실행시 예외 : 스택이 비어있는 경우
@SuppressWarnings("serial")
public class EmptyIntStackException extends RuntimeException {
public EmptyIntStackException() { }
}
// 실행 시 예외 : 스택이 가득 찬 경우
@SuppressWarnings("serial")
public class OverflowIntStackException extends RuntimeException {
public OverflowIntStackException() { }
}
// 생성자
public IntStack(int capacity) {
ptr = 0;
max = capacity;
try {
stk = new int[max]; // 스택 본체용 배열을 생성
} catch(OutOfMemoryError e) { // 생성할 수 없음
max = 0;
}
}
// 스택에 x를 푸시
public int push(int x) throws OverflowIntStackException {
if(ptr >= max) // 스택이 가득 참
throw new OverflowIntStackException();
return stk[ptr++] = x;
}
// 스택에서 데이터를 팝(정상에 있는 데이터를 꺼냄)
public int pop() throws EmptyIntStackException {
if(ptr <= 0) // 스택이 비어있음
throw new EmptyIntStackException();
return stk[--ptr];
}
// 스택에서 데이터를 피크(정상에 있는 데이터를 들여다봄)
public int peek() throws EmptyIntStackException {
if(ptr <= 0) // 스택이 비어있음
throw new EmptyIntStackException();
return stk[ptr - 1];
}
// 스택에서 x를 찾아 인덱스(없으면 -1)를 반환
public int indexOf(int x) {
for(int i=ptr-1; i>=0; i--) { // 정상 쪽에서 선형 검색(스택구조는 위로 쌓이기에)
if(stk[i] == x)
return i; // 검색 성공
}
return -1; // 검색 실패
}
// 스택을 비움
public void clear() {
ptr = 0;
}
// 스택의 용량을 반환
public int capacity() {
return max;
}
// 스택에 쌓여 있는 데이터 수를 반환
public int size() {
return ptr;
}
// 스택이 비어있는가?
public boolean isEmpty() {
return ptr <= 0;
}
// 스택이 가득 찾는가?
public boolean isFull() {
return ptr >= max;
}
// 스택 안의 모든 데이터를 바닥 -> 꼭대기 순서로 출력
public void dump() {
if(ptr <= 0)
System.out.println("스택이 비어있습니다.");
else {
for(int i=0; i<ptr; i++) {
System.out.print(stk[i] + " ");
}
System.out.println();
}
}
}