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

C# Stack.Peek() 메서드 완벽 정리 – 스택 최상위 요소를 제거하지 않고 확인하기

C#의 Stack.Peek() 메서드는 스택(Stack)의 맨 위에 있는 개체를 제거하지 않고 그대로 반환하는 메서드입니다. 스택은 LIFO(Last In, First Out, 후입선출) 구조로 동작하기 때문에, Peek()를 호출하면 가장 마지막에 Push된 요소를 확인할 수 있습니다.

구문

기본 구문은 다음과 같습니다.

public virtual object Peek ();

이 메서드는 매개변수를 받지 않으며, 스택 최상위에 위치한 object를 반환합니다. 주의할 점은 스택이 비어 있는 상태에서 Peek()를 호출하면 InvalidOperationException 예외가 발생한다는 것입니다. 따라서 호출 전에 Count 속성으로 요소 존재 여부를 확인하는 것이 안전합니다.

Peek()와 Pop()의 차이점

  • Peek(): 최상위 요소를 조회만 하며, 스택에서 제거하지 않습니다.
  • Pop(): 최상위 요소를 반환한 후 스택에서 제거합니다.

예제 1

다음은 Stack.Peek() 메서드의 기본적인 사용 예제입니다.

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);
      Console.WriteLine("Element at the top = "+ stack.Peek());

      stack.Push("Ultrabook");
      stack.Push("Cameras");
      stack.Push("Keyboards");

      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("Element at the top = "+ stack.Peek());
      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
Element at the top = Notebook
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Element at the top = Keyboards
Count of elements (updated) = 10
Count of elements (updated) = 0

실행 결과를 보면, 처음에는 마지막에 추가된 "Notebook"이 최상위 요소로 반환됩니다. 이후 세 개의 요소를 더 Push하면 "Keyboards"가 새로운 최상위 요소가 되고, Clear() 호출 후에는 요소 개수가 0으로 변경되는 것을 확인할 수 있습니다.

예제 2

이번에는 Contains(), Clone() 메서드와 함께 Peek()를 활용하는 예제를 살펴보겠습니다.

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);
      Console.WriteLine("Element Speakers is the stack? = "+stack.Contains("Speakers"));

      stack.Push("Headphone");
      stack.Push("Keyboard");
      stack.Push("Earphone");

      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack) {
         Console.WriteLine(val);
      }
      Console.WriteLine("Count of elements (updated) = "+stack.Count);
      Console.WriteLine("Element Alienware is the stack? = "+stack.Contains("Alienware"));

      Stack stack2 = (Stack)stack.Clone();
      Console.WriteLine("\nStack elements...cloned");
      foreach(string val in stack2) {
         Console.WriteLine(val);
      }
      Console.Write("Count of elements (updated) = "+stack2.Count);
      Console.WriteLine("Top of the Stack = "+stack2.Peek());
   }
}

실행 결과

Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element Speakers is the stack? = False
Stack elements...updated
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10
Element Alienware is the stack? = True

Stack elements...cloned
Earphone
Keyboard
Headphone
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements (updated) = 10Top of the Stack = Earphone

이 예제에서는 Clone()으로 복제한 스택에 대해서도 Peek()를 호출하여 복제본의 최상위 요소인 "Earphone"을 확인했습니다. 원본 스택과 복제본은 서로 독립적이므로, 한쪽을 수정해도 다른 쪽에는 영향을 주지 않습니다.

정리

Stack.Peek()는 스택의 최상위 요소를 손쉽게 확인할 수 있는 메서드로, 데이터를 제거하지 않고 조회해야 하는 상황에서 유용하게 사용됩니다. 단, 빈 스택에서 호출하면 예외가 발생하므로 항상 Count 속성 등으로 요소 존재 여부를 먼저 검사하는 습관을 들이는 것이 좋습니다.