Programming skills/자료구조

[자료구조]스택과 큐

제이커브(Jcurve) 2023. 10. 24. 20:56

1. 스택(Stack) : 후입선출의 형태로 가장 마지막에 들어온 값을 가장 먼저 처리하는 알고리즘

예를 들면,  웹페이지 뒤로가기와 같은 것. 내가 마지막에 방문했던 페이지를 뒤로 가기를 누름으로써 가장 먼저 처리하는 형태

스택

using System;
using System.Collections.Generic;

using UnityEngine;

public class Stack : MonoBehaviour 
{
    Stack<string> stack = new Stack<string>();

    public void Start()
    {

    }
    public void Update()
    {
        //데이터 추가
        stack.Push("사과");
        stack.Push("딸기");
        stack.Push("바나나");

        //데이터 제거
        while (stack.Count > 0)
        {
            string data = stack.Pop();
            Debug.Log(data);

        }
    }
}

출력하면 바나나 딸기 사과 , 바나나 딸기 사과로 가장 마지막에 Push된 것이 가장 먼저 출력됨을 알 수 있다.


2. 큐(Queue) : 선입선출의 형태로 들어온 순서대로 처리하는 알고리즘

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Queue : MonoBehaviour
{
    Queue<string> queue = new Queue<string>();
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        queue.Enqueue("사과");
        queue.Enqueue("딸기");
        queue.Enqueue("바나나");

        while(queue.Count > 0)
        {
            //데이터 제거
            string data = queue.Dequeue();
            Debug.Log(data);    
        }
    }
}

출력하면 사과 딸기 바나나 사과 딸기 바나나 순으로 처음 Enqueue된 순서대로 출력함을 알 수 있다.