기본 콘텐츠로 건너뛰기

[DATA STRUCTURE] Stack 스택


What is Stack

A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc.

Basic Operations

  • push() − Pushing (storing) an element on the stack.
  • pop() − Removing (accessing) an element from the stack.
  • peek() − get the top data element of the stack, without removing it.
  • isFull() − check if stack is full.
  • isEmpty() − check if stack is empty.


스택(Stack)의 사용 사례

재귀 알고리즘을 사용하는 경우 스택이 유용하다.


  • 재귀 알고리즘

재귀적으로 함수를 호출해야 하는 경우에 임시 데이터를 스택에 넣어준다.

재귀함수를 빠져 나와 퇴각 검색(backtrack)을 할 때는 스택에 넣어 두었던 임시 데이터를 빼 줘야 한다.

스택은 이런 일련의 행위를 직관적으로 가능하게 해 준다.

또한 스택은 재귀 알고리즘을 반복적 형태(iterative)를 통해서 구현할 수 있게 해준다.

  • 웹 브라우저 방문기록 (뒤로가기)
  • 실행 취소 (undo)
  • 역순 문자열 만들기
  • 수식의 괄호 검사 (연산자 우선순위 표현을 위한 괄호 검사)
  • Ex) 올바른 괄호 문자열(VPS, Valid Parenthesis String) 판단하기
  • 후위 표기법 계산
public class StackTest1 {
    public static void main(String[] args) {
        Stack<Objectstack = new Stack<>();
        int[] arr = {10,20,30,40,50};

        System.out.println(stack.empty()); //True or False

        System.out.println("----------------------------------------------");

        Arrays.stream(arr).forEach(e -> System.out.println(stack.push(e)));

        System.out.println("----------------------------------------------");
        stack.push(7);
        System.out.println(stack); // 10,20,30,40,50,7
        System.out.println("----------------------------------------------");
        stack.pop();
        System.out.println(stack);//pop 7 out

        System.out.println("----------------------------------------------");

        System.out.println("current top is : " +stack.peek()); //top is 50

        System.out.println("----------------------------------------------");

        // 스택에 해당 값이 있는지 확인하고 없으면 -1, 있으면 해당하는 인덱스 값 반환(맨 위부터 1)
        System.out.println("Search(30) index is :" + stack.search(30)); // search element in stack

        System.out.println("----------------------------------------------");

        while (!stack.empty()) {
            // LIFO
            // pop out all elements in stack
            System.out.println(stack.pop());
            
        }
    }
}

References




댓글

이 블로그의 인기 게시물

[DATA STRUCTURE] 큐 QUEUE

큐[QUEUE]의개념 Queue is an abstract data structure, somewhat similar to Stacks.  Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue).  Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first. First In First Out Basic Operation Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the memory. Here we shall try to understand the basic operations associated with queues − enqueue() − add (store) an item to the queue. dequeue() − remove (access) an item from the queue. Few more functions are required to make the above-mentioned queue operation efficient. These are − peek() − Gets the element at the front of the queue without removing it. isfull() − Checks if the queue is full.[Boolean] isempty() − Checks if the queue is empty.[Boolean] 큐의사용 예 너비 우선 탐색(BFS, Breadth-First Search) 구현 처리해야 할 노...

[DATA STRUCTURE] HEAP

What is  Binary Heap ? Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source  Wikipedia ) A  Binary Heap  is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array. Why array based representation for Binary Heap? Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0). public   class   HeapSort  {      void   sort ( int [] ...

SSH 공개키 암호화 설정

★서버명은 임의 공개키 암호화 방식 -[bigdata01,02,03,04]에 동시에 만듬 1.ssh key 만들기 [ ssh-keygen -t rsa ] 2. 아래와 같이 key 생성여부 확인 3. [ cat id_rsa.pub >> authorized_keys ] authorized_keys폴더에 key 암호를 복사   4.폴더 확인 id_rsa [private] 와 id_rsa.pub [public] 이 만들어짐 5 cat authorized_keys 로 검색하면 아래와 같이 암호가 만든 폴더로 들어감. 6.bigdata01에  [ ssh root@bigdata02 cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys ] 를 입력 7.최종적으로 bigdata 02,03,04를 6번 같이 입력하여 authorized_keys 폴더 에 전부 넣음 8. [ scp -rp authorized_keys root@bigdata02:~/.ssh/authorized_keys ]  ★scp= secure copy bigdata 02, 03, 04 설정한 것을 복사해서 보냄. 9. bidata01에서 [ ssh bigdata02 date ] 코드를 쳐서 아래와 같이 나오면 성공