πŸ“š CS [ComputerScience]/πŸ“‚ 자료ꡬ쑰 [DataStructure]

πŸ“‚ [자료ꡬ쑰] μŠ€νƒ(Stack)

Dbswnstjd 2023. 4. 9. 20:55

μŠ€νƒ(Stack) μ΄λž€?

μŠ€νƒμ€ 데이터λ₯Ό μ €μž₯ν•˜κΈ° μœ„ν•œ μžλ£Œκ΅¬μ‘°μž…λ‹ˆλ‹€. 

μŠ€νƒμ˜ LIFO(Last In First Out / First In Last Out) μ΄λΌλŠ” νŠΉμ§•μ„ 가지고 μžˆμŠ΅λ‹ˆλ‹€.

μ»΄ν“¨ν„°μ—μ„œ κ°€μž₯ 많이 μ‚¬μš©λ˜λŠ” 자료ꡬ쑰라고 해도 무방할 만큼 맀우 많이 μ“°μ΄λŠ” μžλ£Œκ΅¬μ‘°μž…λ‹ˆλ‹€. 

μŠ€λ§ˆνŠΈν°μ—μ„œ 'λ’€λ‘œ κ°€κΈ°' λ²„νŠΌμ„ λˆŒλ €μ„ λ•Œ ν˜„μž¬ μ‹€ν–‰ν•˜κ³  μžˆλŠ” 앱이 μ’…λ£Œλ˜κ³  μ§μ „μ˜ 앱이 λ‚˜νƒ€λ‚˜λŠ”λ° 이 λ•Œ μ‚¬μš©λ˜λŠ” 것이 μŠ€νƒμž…λ‹ˆλ‹€. 

μŠ€νƒ / 큐

μŠ€νƒμ˜ ꡬ쑰와 μ‚¬μš©

μŠ€νƒμ€ λ§ˆμ§€λ§‰μ— λ“€μ–΄μ˜¨ 데이터가 κ°€μž₯ λ¨Όμ € λ‚˜μ˜€κ²Œ λ©λ‹ˆλ‹€. 

μŠ€νƒμ—μ„œ μ‚¬μš©λ˜λŠ” ν•¨μˆ˜λ‘œλŠ” λŒ€ν‘œμ μœΌλ‘œ pop / push / peek / isFull / isEmpty κ°€ μžˆμŠ΅λ‹ˆλ‹€. 

  • Push() : μŠ€νƒμ— 값을 λ„£λŠ” ν•¨μˆ˜ 
  • Pop() : μŠ€νƒμ˜ Top μœ„μΉ˜μ— μžˆλŠ” 데이터λ₯Ό 좜λ ₯ν•˜λŠ” ν•¨μˆ˜ 
  • Peek() : ν‘Έμ‰¬μ˜ κ°€μž₯ λ§ˆμ§€λ§‰μ— μž…λ ₯된 κ°’, 즉 탑 μœ„μΉ˜μ˜ 값을 ν™•μΈν•˜λŠ” ν•¨μˆ˜ 
  • isFull() : μŠ€νƒμ΄ 꽉 μ°ΎλŠ”μ§€ ν™•μΈν•˜λŠ” ν•¨μˆ˜ 
  • isEmpty() : μŠ€νƒμ΄ ν˜„μž¬ λΉ„μ–΄μžˆλŠ”μ§€ ν™•μΈν•˜λŠ” ν•¨μˆ˜

 

파이썬으둜 μŠ€νƒ ν™œμš©ν•˜κΈ°

νŒŒμ΄μ¬μ€ 기본적으둜 μŠ€νƒ 자료ꡬ쑰λ₯Ό μ§€μ›ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. κ·Έλž˜μ„œ 리슀트λ₯Ό 톡해 μŠ€νƒμ„ κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

# μŠ€νƒ 자료ꡬ쑰
stack = []
for i in range(5):
    stack.push(i)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack)

κ²°κ³Ό

appendλŠ” μŠ€νƒμ˜ push와 κ°™λ‹€κ³  보면 λ©λ‹ˆλ‹€. 

pop을 톡해 κ°€μž₯ top에 μžˆλŠ” 데이터λ₯Ό λΊλ‹ˆλ‹€. 

 

μžλ°”λ‘œ μŠ€νƒ ν™œμš©ν•˜κΈ° 

package DataStructure;
import java.util.Stack;

import javax.lang.model.element.Element;

public class DataStructureStack {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();//push, pop, peek - μ΅œκ·Όμ— 넣은 κ°’ 좜λ ₯, empty, seach 지원
        for(int i=1; i<=5 ; i++) {
            stack.push(i);
            System.out.println(stack.peek());
        } //1, 2, 3, 4, 5 좜λ ₯ 
        stack.pop();
        System.out.println("Pop()");
        System.out.println(stack.peek());    //4좜λ ₯
        System.out.println(stack.search(3));    //2좜λ ₯
        System.out.println(stack.empty());    //false좜λ ₯
    }

}

μžλ°”λŠ” Stack 클래슀λ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€.