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

C# Stack.Push() 메서드 완벽 가이드 – 스택 맨 위에 요소 추가하기

C#의 Stack.Push() 메서드는 스택(Stack) 컬렉션의 맨 위(top)에 새로운 개체를 삽입할 때 사용합니다. 스택은 LIFO(후입선출, Last-In-First-Out) 구조를 따르기 때문에, Push()로 추가한 요소는 항상 스택의 최상단에 위치하게 됩니다.

구문

Push() 메서드의 기본 구문은 다음과 같습니다.

public virtual void Push(object ob);

여기서 매개변수 ob는 스택에 추가할 개체를 의미합니다. 이 메서드는 별도의 값을 반환하지 않으며(void), 내부 용량이 가득 찬 상태에서 요소를 추가하면 용량이 자동으로 확장됩니다. 또한 Push() 메서드에는 null 값도 허용됩니다.

예제 1: 정수 요소 추가하기

다음 예제에서는 정수형 요소들을 스택에 Push하고, 새로운 요소를 추가한 뒤 Count 속성 값이 어떻게 변하는지 확인해 보겠습니다. 아울러 Clone() 메서드로 스택의 복제본을 만들어 함께 살펴봅니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push(150);
        stack.Push(300);
        stack.Push(500);
        stack.Push(750);
        stack.Push(1000);
        stack.Push(1250);
        stack.Push(1500);
        stack.Push(2000);
        stack.Push(2500);
        Console.WriteLine("Stack elements...");
        foreach(int val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        stack.Push(3000);
        stack.Push(3500);
        stack.Push(4000);
        Console.WriteLine("\nStack elements...updated");
        foreach(int val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
        Stack stack2 = (Stack)stack.Clone();
        Console.WriteLine("\nStack elements...cloned");
        foreach(int val in stack2) {
            Console.WriteLine(val);
        }
        Console.Write("Count of elements in cloned stack(updated) = "+stack2.Count);
    }
}

실행 결과

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

Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9

Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12

Stack elements...cloned
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements in cloned stack(updated) = 12

실행 결과를 보면, Push()로 새 요소를 추가할 때마다 해당 요소가 스택의 맨 위에 쌓이는 것을 알 수 있습니다. foreach 루프는 스택을 top부터 차례대로 열거하기 때문에 출력 순서도 역순으로 표시됩니다. 처음 9개였던 요소 수가 3개의 요소를 추가한 후 12개로 늘어난 점에서, Count 속성이 실시간으로 갱신되는 것도 확인할 수 있습니다. Clone()으로 복제한 스택 역시 원본과 동일한 요소와 개수를 유지합니다.


예제 2: 문자열 요소 추가 후 Clear()로 비우기

이번에는 문자열 데이터를 스택에 Push하고, 이후 Clear() 메서드를 호출하여 스택을 완전히 비우는 과정까지 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
    public static void Main() {
        Stack stack = new Stack();
        stack.Push("Inspiron");
        stack.Push("Alienware");
        stack.Push("Projectors");
        stack.Push("Monitors");
        stack.Push("XPS");
        stack.Push("Laptop");
        stack.Push("Notebook");
        Console.WriteLine("Stack elements...");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements = "+stack.Count);
        stack.Push("Ultrabook");
        stack.Push("Cameras");
        stack.Push("Keyboards");
        Console.WriteLine("\nStack elements...updated");
        foreach(string val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
        stack.Clear();
        Console.Write("Count of elements (updated) = "+stack.Count);
    }
}

실행 결과

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

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7

Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Count of elements (updated) = 0

문자열 요소 역시 동일한 LIFO 순서로 출력됩니다. 가장 마지막에 Push한 "Keyboards"가 맨 위에 위치하는 것을 볼 수 있으며, Clear() 호출 후 Count 값이 0으로 초기화되어 스택이 완전히 비워진 것을 확인할 수 있습니다.


정리

  • Stack.Push()는 스택의 맨 위에 개체를 삽입하는 메서드입니다.
  • null 값도 Push할 수 있으며, 반환값은 없습니다(void).
  • 요소를 추가하면 Count 속성 값이 증가하고, 필요 시 내부 용량이 자동으로 확장됩니다.
  • foreach 문으로 스택을 열거하면 가장 나중에 Push된 요소부터 순서대로 출력됩니다.