본문 바로가기
C++ 200제/코딩 IT 정보

C# 스택 예제, Stack 클래스와 Push 등 사용법

by vicddory 2017. 4. 15.

C# 스택 예제, Stack 클래스와 Push 등 사용법

 

Stack. 스택은 LIFO 콜렉션이며 강력한 후입선출(last-in-first-out) 데이터 구조체입니다. 더욱 빠른 파서와 재귀 알고리즘 구현에도 도움이 됩니다.

 

Push. 원소(element)를 넣어 사용한다는 의미로, 컴퓨터 사이언스 측면에선 상단에 추가한다는 뜻입니다. (add to the top) 다음 예제의 함수는 스택에 쌓인 integers를 리턴합니다.

using System;
using System.Collections.Generic;
 
class Program
{
    static Stack<int> GetStack()
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(100);
        stack.Push(1000);
        stack.Push(10000);
 
        return stack;
    }
 
    static void Main()
    {
        var stack = GetStack();
        Console.WriteLine("--- Stack contents ---");
 
        foreach (int i in stack)
        {
            Console.WriteLine(i);
        }
    }
}

Output

 

--- Stack contents ---

10000

1000

100

 

In this program. 3개의 integer를 보유한 스택 지역 변수는 마지막에 10,000이 추가되었고 이 값이 맨 처음 출력되었습니다.

Tip: 첫 번째 출력값이 10,000입니다. 이는 전형적인 LIFO의 형태임을 나타냅니다.

 

LIFO: 마지막에 추가된 값(with Push)이 제일 먼저 제거(with Pop)됩니다.

 

Pop. 스택의 Pop 메소드와 Peek 메소드를 확인합니다. Pop을 호출하면 top에 위치한 요소가 리턴되며, 삭제됩니다.

Also: Peek를 사용하면 Pop과 같은 결과가 나오지만, 요소를 삭제하진 않습니다.

using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Get the stack.
        // ... See above definition of this method.
        Stack<int> stack = GetStack();
 
        // Pop the top element.
        int pop = stack.Pop();
 
        // Write to the console.
        Console.WriteLine("--- Element popped from top of Stack ---");
        Console.WriteLine(pop);
 
        // Now look at the top element.
        int peek = stack.Peek();
        Console.WriteLine("--- Element now at the top ---");
        Console.WriteLine(peek);
    }
}
Output --- Element popped from top of Stack ---10000--- Element now at the top ---

 

1000

C# 스택 예제, Stack 클래스와 Push 등 구현 방법
[프로그래밍 기초] LIFO, Last In First Out 자료구조

 

Pop and Peek. 둘 다 가장 최근에 추가된 요소를 가리키는 스택의 top 요소를 리턴합니다. 그러나 Peek은 스택의 요소를 삭제하지 않습니다. Pop과는 달리 그저 값을 리턴하는 것뿐입니다.

 

ToArray(). 이 함수를 이용하면 스택의 요소를 배열로 복사할 수 있습니다.

 

Clear, count. Clear를 사용해 스택의 카운트를 0으로 만듭니다. 스택이 null일 경우를 제외하고 예외 상황(exception)은 발생하지 않습니다. Count 함수는 별도의 인자가 필요하지 않은데, 이것은 Clear도 마찬가지입니다.

using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Get the stack [See method definition above]
        Stack<int> stack = GetStack();
 
        // Count the number of elements in the Stack
        int count = stack.Count;
        Console.WriteLine("--- Element count ---");
        Console.WriteLine(count);
 
        // Clear the Stack
        stack.Clear();
        Console.WriteLine("--- Stack was cleared ---");
        Console.WriteLine(stack.Count);
    }
}

Output

 

--- Element count ---

3

--- Stack was cleared ---

0

 

Using null stacks. 먼저, 스택은 string 형태로 null을 받아들입니다. 또한, null을 할당하여 Clear() 함수처럼 사용할 수도 있습니다. 이 경우 약간의 성능 차이가 존재합니다.

Also. 위의 사항은 Stack<string>과 같이 선언했을 때의 설명입니다. Stack<int> 형태로 null을 Push하면 오류가 발생해요.

 

Exception. 아마도 처음 사용할 때 주로 발생하지 않을까요. 비어있는 스택의 객체에 Pop, Peek를 호출하면 Runtime 에러가 발생합니다. 그러나 이런 문제는 쉽게 해결됩니다.

 

To work around this problem. Count() 함수를 사용하세요. 아래의 예제는 위에서 설명한 상황을 올바르게 해결하는 방법의 하나입니다.

using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Create an empty Stack.
        var stack = new Stack<int>();
 
        try
        {
            // This throws an exception.
            int pop = stack.Pop();
        }
        catch (Exception ex)
        {
            Console.WriteLine("--- Exception raised by Pop ---");
            Console.WriteLine(ex.ToString());
        }
 
        // Here we safely Pop the stack.
        if (stack.Count > 0)
        {
            int safe = stack.Pop();
        }
        else
        {
            Console.WriteLine("--- Avoided exception by using Count method ---");
        }
    }
}

Output

 

--- Exception raised by Pop ---

System.InvalidOperationException: Stack empty.

    ...

    ...

--- Avoided exception by using Count method

 

Copy, search. 다른 형태의 저장소를 이용해 소스를 간략화할 수 있습니다. 스택의 생성자는 IEnumerable 인터페이스를 이용해 다양한 자료형을 처리합니다.

Also. 아래 예제에선 Contains 함수를 사용했습니다. 이 함수는 스택의 요소에서 인자를 찾으면 true를 리턴합니다.

using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // An example string array.
        string[] values = { "Dot", "Net", "Perls" };
 
        // Copy an array into a Stack.
        var stack = new Stack<string>(values);
 
        // Display the Stack.
        Console.WriteLine("--- Stack contents ---");
 
        foreach (string value in stack)
        {
            Console.WriteLine(value);
        }
 
        // See if the stack contains "Perls"
        Console.WriteLine("--- Stack Contains method result ---");
 
        bool contains = stack.Contains("Perls");
        Console.WriteLine(contains);
    }
}

Stack Example Output

 

--- Stack contents ---

Perls

Net

Dot

--- Stack Contains method result ---

True

이 예제에선 일반적인 자료형만을 다뤘습니다. 클래스 객체나 다른 요소 간의 비교와 처리는 다루지 않았습니다.

 

c# stack 스택 힙 lifo
[프로그래밍 기초] LIFO, Last In First Out 자료구조

 

다른, 조금 긴 마지막 C# 스택 예제

using System;
using System.Collections;
 
namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Stack st = new Stack();
         st.Push('A');
         st.Push('M');
         st.Push('G');
         st.Push('W');
 
         Console.WriteLine("Current stack: ");
 
         foreach (char c in st)
         {
            Console.Write(c + " ");
         }
 
         Console.WriteLine();
         
         st.Push('V');
         st.Push('H');
 
         Console.WriteLine("The next poppable value in stack: ", st.Peek());
         Console.WriteLine("Current stack: ");
 
         foreach (char c in st)
         {
            Console.Write(c + " ");
         }
 
         Console.WriteLine();
         Console.WriteLine("Removing values ");
 
         st.Pop();
         st.Pop();
         st.Pop();
 
         Console.WriteLine("Current stack: ");
 
         foreach (char c in st)
         {
            Console.Write(c + " ");
         }
      }
   }
}

Current stack: 

W G M A

 

The next poppable value in stack: H

Current stack: 

H V W G M A

 

Removing values

Current stack: 

G M A

 

Dotnetperls - stack [클릭]

C# - Stack Class [클릭]

C# 스택 예제, Stack 클래스와 Push 등 사용법

댓글