>  기사  >  백엔드 개발  >  C# 스택

C# 스택

WBOY
WBOY원래의
2024-09-03 15:30:28541검색

후입선출 방식으로 표현되는 객체의 집합을 스택(Stack)이라고 하며 프로그램의 필요에 따라 스택에 요소가 추가됨에 따라 증가하는 컬렉션이므로 동적 컬렉션이며 동일한 유형과 다른 유형의 요소가 모두 스택에 저장될 수 있으며, 스택에 요소를 추가하는 프로세스를 스택에 요소를 푸시(push)라고 하며, 스택에서 요소를 제거하는 프로세스를 스택에서 요소를 팝핑(popping)이라고 합니다. 이 스택은 시스템 아래에 있습니다. 컬렉션 네임스페이스.

구문:

C# 스택의 구문은 다음과 같습니다.

Stack stack_name = new Stack();

여기서 stack_name은 stack.l의 이름입니다

C#의 스택 기능

  • 후입선출 순서로 스택의 요소에 액세스해야 할 때마다 우리는 Stack이라는 개체 컬렉션을 사용합니다.
  • 스택에 요소를 추가하는 과정을 스택에 푸시(push)라고 하며, 스택에서 요소를 제거하는 과정을 스택에서 요소 팝핑(popping)이라고 합니다.
  • 스택에 요소가 추가됨에 따라 스택 크기가 증가하므로 스택은 요소의 동적 모음입니다.
  • 스택이 담을 수 있는 요소 수를 스택 용량이라고 합니다. 스택에 요소가 추가됨에 따라 스택의 크기가 증가함에 따라 재할당을 통해 스택의 용량도 증가합니다.
  • 스택에 중복 요소가 허용될 수 있습니다.
  • Null은 스택에서 유형 참조에 대한 유효한 값으로 허용됩니다.

C#의 Stack에는 여러 생성자가 있습니다. 그들은:

  • Stack(): 스택 클래스의 새 인스턴스가 초기화되고 초기 용량이 기본값인 비어 있습니다.
  • Stack(ICollection): 매개변수로 지정된 컬렉션에서 가져온 요소로 구성된 스택 클래스의 새 인스턴스가 초기화되며 초기 용량은 가져온 요소 수와 동일합니다. 매개변수로 지정된 컬렉션에서.
  • Stack(Int32): 초기 용량이 매개변수로 지정된 초기 용량이거나 기본값인 초기 용량인 비어 있는 스택 클래스의 새 인스턴스가 초기화됩니다.

C# 스택의 메서드

C#의 Stack에는 여러 가지 메서드가 있습니다. 그들은:

  • Clear(): Clear() 메서드를 사용하여 스택의 개체를 제거합니다.
  • Push(Object): Push(Object) 메서드를 사용하여 매개변수로 지정된 객체를 스택 최상단에 삽입합니다.
  • Contains(Object): Contains(Object) 메서드는 스택에 요소가 있는지 확인하는 데 사용됩니다.
  • Peek(): 스택 상단에 지정된 개체가 반환되지만 Peek() 메서드를 사용하여 제거되지는 않습니다.
  • Pop(): 스택 상단에 지정된 개체가 반환되고 Pop() 메서드를 사용하여 제거됩니다.

다음은 C# 스택의 예입니다.

예시 #1

Push() 메서드, Pop() 메서드, Peek() 메서드, Contains() 메서드 및 Clear() 메서드를 시연하려면 아래 예제 프로그램을 고려하세요.

코드:

using System;
using System.Collections;
//a class called program is defined
class program
{
//main method is called
public static void Main()
{
//a new stack is created
Stack mystk = new Stack();
//Adding the elements to the newly created stack
mystk.Push("India");
mystk.Push("USA");
mystk.Push("Canada");
mystk.Push("Germany");
//displaying the elements of the stack using foreach loop
Console.Write("The elements in the Stack are : ");
foreach(varele in mystk)
{
Console.WriteLine(ele);
}
//using contains() method to check if an element is present in the stack or not
Console.WriteLine(mystk.Contains("Germany"));
// The count of the elements in the stack is displayed
Console.Write("The count of elements in the Stack are : ");
Console.WriteLine(mystk.Count);
// displaying the top most element of the stack using Peek() method
Console.WriteLine("The topmost element in the stack is  : " + mystk.Peek());
//Using pop() method to remove the top element in the stack
Console.WriteLine("the element of the stack that is going to be removed" + " is: {0}",mystk.Pop());
Console.Write("The elements in the Stack after using pop() method are : ");
foreach(var el in mystk)
{
Console.WriteLine(el);
}
Console.Write("The count of elements in the Stack after using pop() method is : ");
Console.WriteLine(mystk.Count);
//using Clear() method to remove all the elements in the stack
mystk.Clear();
Console.Write("The count of elements in the Stack after using Clear() method is : ");
Console.WriteLine(mystk.Count);
}
}

출력:

C# 스택

위 프로그램에는 program이라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 새 스택이 생성됩니다. 그런 다음 요소는 Push() 메서드를 사용하여 새로 생성된 스택에 추가됩니다. 그런 다음 새로 생성된 스택의 요소가 foreach 루프를 사용하여 표시됩니다. 그런 다음 Contains() 메서드를 사용하여 스택에 요소가 있는지 확인합니다. 그런 다음 count() 메서드를 사용하여 스택에 있는 요소의 개수를 표시합니다. 그런 다음 Peek() 메서드를 사용하여 스택의 최상위 요소가 표시됩니다. 그런 다음 Pop() 메서드를 사용하여 스택의 최상위 요소가 제거됩니다. 그런 다음 Pop() 메서드를 사용한 후 다시 요소 수와 스택 요소가 표시됩니다. 그런 다음 Clear() 메서드를 사용하여 스택의 모든 요소를 ​​제거합니다. 그런 다음 Clear() 메서드를 사용한 후 요소 수와 스택 요소가 다시 표시됩니다. 프로그램의 출력은 위의 스냅샷에 표시됩니다.

  • Clone(): A shallow copy of the stack is created using the Clone() method.
  • Equals(Object): The Equals(Object) method is used to determine if the object specified as the parameter is equal to the current object.
  • Synchronized(Stack): A synchronized wrapper for the stack is returned using the Synchronized(Stack) method.
  • CopyTo(Array,Int32): The stack is copied into an array which is one dimensional with the index of the array specified as a parameter.
  • ToArray(): The stack is copied to a new array using ToArray() method.
  • GetType(): The type of the current instance is obtained using GetType() method.
  • ToString(): A string representing the current object is returned using ToString() method.
  • GetEnumerator(): An IEnumerator for the stack is returned using GetEnumerator() method.
  • GetHashCode(): The GetHashCode() method is the hash function by default.
  • MemberwiseClone(): A shallow copy of the current object is created using MemberwiseClone() method.

Example #2

Consider the example program below to demonstrate Clone() method, Equals() method, Synchronized() method, CopyTo() method, ToArray() method, GetType() method and GetEnumerator() method:

Code:

using System;
using System.Collections;
//a class called program is defined
class program
{
// Main Method is called
public static void Main(string[] args)
{
// creating a new stack
Stack mystk = new Stack();
mystk.Push("India");
mystk.Push("USA");
mystk.Push("Canada");
mystk.Push("Germany");
Console.Write("The elements in the Stack are : ");
foreach(varele in mystk)
{
Console.WriteLine(ele);
}
// a clone of the newly created stack is created
Stack mystk1 = (Stack)mystk.Clone();
// the top most element of the clone of the newly created stack is removed using pop() method
mystk1.Pop();
Console.Write("The elements in the clone of the Stack after using pop() method are : ");
//the elements of the clone of the newly created stack is displayed
foreach(Object ob in mystk1)
Console.WriteLine(ob);
//checking if the elements of the clone of the newly created stack and the newly created stack are equal or not
Console.Write("The elements in the clone of the Stack and the stack are equal or not : ");
Console.WriteLine(mystk.Equals(mystk1));
//Checking if the clone of the newly created stack and the newly created stack is synchronised or not
Console.WriteLine("The Clone of the newly created stack is {0}.", mystk1.IsSynchronized ? "Synchronized" : "Not Synchronized");
Console.WriteLine("The newly created stack is {0}.", mystk.IsSynchronized ? "Synchronized" : "Not Synchronized");
//a new array of strings is created and the newly created stack is assigned to this array
string[] arra = new string[mystk.Count];
// The elements of the newly created stack is copied to the array
mystk.CopyTo(arra, 0);
// the elements of the array are displayed
Console.Write("The elements of the array copied from the newly created stack are : ");
foreach(string st in arra)
{
Console.WriteLine(st);
}
//converting the elements of the newly created stack to array using toarray() method
Object[] ar1 = mystk.ToArray();
Console.Write("The elements of the array copied from the newly created stack by using ToArray() method are :");
//the elements of the array are displayed
foreach(Object st1 in ar1)
{
Console.WriteLine(st1);
}
Console.WriteLine("The type of newly created stack before using "+
"ToStringMethod is: "+mystk.GetType());
Console.WriteLine("The type of newly created stack after using "+
"ToString Method is: "+mystk.ToString().GetType());
Console.Write("The elements of the newly created stack after using GetEnumerator() method are : ");
//Getenumerator() method is used to obtain the enumerator of thestack
IEnumeratorenume = mystk.GetEnumerator();
while (enume.MoveNext())
{
Console.WriteLine(enume.Current);
}
}
}

Output:

C# 스택

In the above program, a class called program is defined. Then the main method is called. Then a new stack is created. Then the clone of the newly created stack is created by using the clone() method. Then the topmost element of the clone of the newly created stack is removed using the pop() method. Then the elements of the clone of the newly created method are displayed. Then Equals() method is used to check if the newly created stack and the clone of the newly created stack are equal or not. Then the synchronized() method is used to check if the newly created stack and the clone of the newly created stack are synchronized or not. Then Copyto() method is used to copy the newly created stack to an array and the elements of the array are displayed. Then ToArray() method is used to copy the newly created stack to another array and then the elements of the array are displayed. Then GetType() method is used to obtain the type of the newly created stack. Then ToString() method is used to convert the type stack to string. Then GetEnumerator() method is used to obtain the IEnumerator of the stack. The output of the program is shown in the snapshot above.

위 내용은 C# 스택의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C#의 메타데이터다음 기사:C#의 메타데이터