Stack 자료구조 구현
FILO : first in last out
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
import java.util.EmptyStackException;
/**
- Stack 자료구조 구현
- FILO : first in last out
*/
class Stack<T> {
class Node<t> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
private Node<T> top;
public void push(T data){
// 새로운 노드 생성
Node<T> tmp = new Node<T>(data);
// 새로운 노드의 참조 포인터 노드는 가장 위에 있는 노드
tmp.next = top;
// 포인터 이동
top = tmp;
}
public T pop() {
// top 노드가 null 일 경우 Exception if (top == null) {
throw new EmptyStackException();
}
// top 노드 데이터 임시 저장
T item = top.data;
// top 노드는 다음 노드로 이동 (먼저 들어온 노드)
top = top.next;
return item;
}
public T peek() {
if (top == null) {
throw new EmptyStackException();
}
return top.data;
}
public boolean isEmpty(){
return top == null;
}
}
public class test {
public static void main (String[] args) {
System.out.println("hello world");
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek());
stack.pop();
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
stack.pop();
stack.pop();
System.out.println(stack.isEmpty());
}
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.