Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 스택(Stack) 생성하는 방법 – 예제 코드로 쉽게 배우기

C#에서 스택(Stack)은 LIFO(Last In First Out, 후입선출) 방식으로 데이터를 저장하는 대표적인 컬렉션입니다. 즉, 가장 나중에 추가된 요소가 가장 먼저 제거되는 구조로, 되돌리기(Undo) 기능이나 호출 기록 관리 같은 상황에서 유용하게 활용됩니다. C#에서는 System.Collections.Generic 네임스페이스의 Stack<T> 클래스를 사용하여 간단히 스택을 만들 수 있습니다.

스택 생성 기본 예제

다음 예제에서는 Stack<int> 객체를 선언한 뒤, Push() 메서드로 여러 개의 정수를 추가하고, foreach 문으로 전체 요소를 출력합니다. 또한 Count 속성으로 요소 개수를 확인하고, Contains() 메서드로 특정 값의 존재 여부를 검사합니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(100);
      stack.Push(150);
      stack.Push(175);
      stack.Push(200);
      stack.Push(225);
      stack.Push(250);
      stack.Push(300);
      stack.Push(400);
      stack.Push(450);
      stack.Push(500);
      Console.WriteLine("Elements in the Stack:");
      foreach(var val in stack){
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements in the Stack = "+stack.Count);
      Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Elements in the Stack:
500
450
400
300
250
225
200
175
150
100
Count of elements in the Stack = 10 Does Stack has the element 400?= True

결과 분석

출력 결과를 보면 100부터 순서대로 Push()했음에도 불구하고, 마지막에 추가된 500이 가장 먼저 출력되는 것을 확인할 수 있습니다. 이것이 바로 스택의 핵심 특징인 후입선출(LIFO) 구조입니다. 아울러 Count는 현재 저장된 요소 수인 10을 반환하고, Contains(400)은 해당 값이 존재하기 때문에 True를 반환합니다.

두 번째 예제

이번에는 10부터 100까지 10씩 증가하는 값을 스택에 저장한 뒤, 요소 개수와 전체 내용을 출력해 보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(10);
      stack.Push(20);
      stack.Push(30);
      stack.Push(40);
      stack.Push(50);
      stack.Push(60);
      stack.Push(70);
      stack.Push(80);
      stack.Push(90);
      stack.Push(100);
      Console.WriteLine("Count of elements = "+stack.Count);
      Console.WriteLine("Elements in Stack...");
      foreach (int res in stack){
         Console.WriteLine(res);
      }
   }
}

출력 결과

실행 결과는 다음과 같습니다.

Count of elements = 10
Elements in Stack...
100
90
80
70
60
50
40
30
20
10

핵심 정리

  • Push(T item): 스택의 맨 위에 새 요소를 추가합니다.
  • Pop(): 스택의 맨 위 요소를 제거하고 반환합니다.
  • Peek(): 요소를 제거하지 않고 맨 위 값을 확인합니다.
  • Contains(T item): 특정 값이 스택에 있는지 여부를 반환합니다.
  • Count: 스택에 저장된 요소의 개수를 나타냅니다.

이처럼 C#의 Stack<T> 클래스는 몇 줄의 코드만으로 후입선출 구조의 자료관리를 손쉽게 구현할 수 있으며, 데이터 삽입·조회·검색을 위한 다양한 메서드를 기본적으로 제공합니다.