Records rather than Memories

스택 Stack 본문

Software/JAVA

스택 Stack

Downer 2019. 11. 12. 15:03

컴퓨터 공학에서 가장 기본이 되는 자료구조이다.  stack이라는 이름 처럼 차곡 차곡 쌓는다는 의미인데 아래부터 하나씩 데이터를 쌓아나가는 방식이다.

즉, LIFO(Last In First Out) 방식으로 구현되는 자료구조이다.

또 다른 기본 자료구조로 큐(queue)가 있는데 서로 상이한 부분이 있으므로 여기서 잠시 살펴보면 스택은 입구와 출구가 같고 큐는 입구와 출구가 반대편에 있는 형태이다.

 

 

그림으로 표현된 스택 구조를 보자.

 

그림 처럼 push는 가장 위에 데이터를 입력하는 것이다.

pop은 가장 위 데이터를 내보내는 것이다.

peek : 맨 마지막 데이터를 보는 것이다.

isEmpty : 데이터가 있는지 없는지 확인한다.

'

 

 

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
import java.util.EmptyStackException;
 
class Stacking<T>{
    class Node<T>{
        private T data;
        private Node<T> next;
        
        public Node(T data) {
            this.data = data;
        }
    }
    
    private Node<T> top;
    
    public T pop() {
        if(top == null) {
            throw new EmptyStackException();
        }
        
        T item = top.data;
        top = top.next;
        return item;
    }
    
    public void push(T item) {
        Node<T> t = new Node<T>(item);
        t.next = top;
        top = t;
    }
    
    public T peek() {
        if(top == null) {
            throw new EmptyStackException();
        }
        return top.data;
    }
    
    public boolean isEmpty() {
        return top == null;
    }
}
 
public class Stack {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Stacking <Integer> numbers = new Stacking<Integer>();
        numbers.push(1);
        numbers.push(2);
        numbers.push(3);
        System.out.println(numbers.pop());
        numbers.push(4);
        System.out.println(numbers.peek());
        System.out.println(numbers.isEmpty());
 
    }
 
}
 
cs

 

'Software > JAVA' 카테고리의 다른 글

[java] 너비 우선 탐색 (BFS)  (0) 2019.11.15
[java] 큐 Queue  (0) 2019.11.15
힙 정렬 Heap sort  (0) 2019.11.10
합병 정렬 Merge sort  (0) 2019.11.09
퀵 정렬 Quick sort  (0) 2019.11.08
Comments