Pile C# avec exemples Push & Pop

โšก Rรฉsumรฉ intelligent

Stack in C# is a collection from the System.Collections namespace that follows the last in, first out (LIFO) principle, where the Push method adds an element to the top and the Pop method removes it.

  • ๐Ÿ“š LIFO concept: A stack works like a pile of books, so the last element pushed is the first one removed.
  • โž• Push and Pop: The Push method adds an element to the top of the stack, and the Pop method removes and returns that topmost element.
  • ๐Ÿ‘€ Peek, Count, Contains: The Peek method reads the top element without removing it, while Count and Contains report size and membership.
  • ๐Ÿงช Exemples rรฉsolus : Two console programs demonstrate Push with Count and Contains, then Pop, so you can trace the LIFO order.
  • ๏ธ Generic stack: The Stack<T> class in System.Collections.Generic adds compile-time type safety and avoids boxing for new C# code.
  • ๐Ÿค– Aide ร  l'IA : GitHub Copilot scaffolds C# Stack operations, and ML.NET reads data through typed collections instead of a non-generic stack.

Pile C#

Quโ€™est-ce que Stack en C# ?

La pile est une collection de cas particuliers qui reprรฉsente un concept du dernier entrรฉ, premier sorti (LIFO). Pour dโ€™abord comprendre LIFO, prenons un exemple. Imaginez une pile de livres, chaque livre รฉtant superposรฉ.

Le concept du dernier entrรฉ, premier sorti dans le cas des livres signifie que seul le livre le plus haut peut รชtre retirรฉ de la pile de livres. Il n'est pas possible de retirer un livre entre les deux, car cela perturberait le positionnement de la pile.

Donc dans C#, la pile fonctionne รฉgalement de la mรชme maniรจre. Les รฉlรฉments sont ajoutรฉs ร  la pile, les uns sur les autres. Le processus dโ€™ajout dโ€™un รฉlรฉment ร  la pile est appelรฉ opรฉration push. Pour supprimer un รฉlรฉment d'une pile, vous pouvez รฉgalement supprimer l'รฉlรฉment le plus haut de la pile. Cette opรฉration est connue sous le nom de pop.

Examinons plus en dรฉtail les opรฉrations disponibles pour la collection Stack.

Dรฉclaration de la pile

Une pile est crรฉรฉe ร  l'aide du type Stack Data. Le mot clรฉ ยซ new ยป est utilisรฉ pour crรฉer un objet dโ€™une Stack. L'objet est ensuite affectรฉ ร  la variable st.

Stack st = new Stack()

Ajout d'รฉlรฉments ร  la pile

La mรฉthode push est utilisรฉe pour ajouter un รฉlรฉment sur la pile. La syntaxe gรฉnรฉrale de l'instruction est donnรฉe ci-dessous.

Stack.push(element)

Supprimer des รฉlรฉments de la pile

La mรฉthode pop est utilisรฉe pour supprimer un รฉlรฉment de la pile. L'opรฉration pop renverra l'รฉlรฉment le plus haut de la pile. La syntaxe gรฉnรฉrale de l'instruction est donnรฉe ci-dessous

 Stack.pop()

que vous avez

Cette propriรฉtรฉ est utilisรฉe pour obtenir le nombre d'รฉlรฉments dans la pile. Vous trouverez ci-dessous la syntaxe gรฉnรฉrale de cette instruction.

Stack.Count

Inclus

Cette mรฉthode est utilisรฉe pour voir si un รฉlรฉment est prรฉsent dans la Stack. Vous trouverez ci-dessous la syntaxe gรฉnรฉrale de cette instruction. L'instruction renverra vrai si l'รฉlรฉment existe, sinon elle renverra la valeur faux.

Stack.Contains(element)

Voyons maintenant que cela fonctionne au niveau du code. Tout le code mentionnรฉ ci-dessous sera รฉcrit dans notre Application console. Le code sera รฉcrit dans notre fichier Program.cs.

Dans le programme ci-dessous, nous รฉcrirons le code pour voir comment nous pouvons utiliser les mรฉthodes mentionnรฉes ci-dessus.

Exemple 1 : mรฉthode Stack.Push()

Dans cet exemple, nous verrons

  • Comment une pile est crรฉรฉe.
  • Comment afficher les รฉlรฉments de la pile, et utiliser les mรฉthodes Count et Contain.

Pile en C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Stack st = new Stack();
   st.Push(1);
   st.Push(2);
   st.Push(3);

   foreach (Object obj in st)
   {
    Console.WriteLine(obj);
   }
    Console.WriteLine(); Console.WriteLine();
    Console.WriteLine("The number of elements in the stack " +st.Count);
    Console.WriteLine("Does the stack contain the elements 3 "+st.Contains(3));
    Console.ReadKey();
  }
 }
}

Code Explication:-

  1. La premiรจre รฉtape permet de dรฉclarer la Stack. Ici, nous dรฉclarons ยซ st ยป comme variable pour contenir les รฉlรฉments de notre pile.
  2. Ensuite, nous ajoutons 3 รฉlรฉments ร  notre pile. Chaque รฉlรฉment est ajoutรฉ via la mรฉthode Push.
  3. Maintenant, puisque les รฉlรฉments de la pile ne sont pas accessibles via la position d'index comme le liste des tableaux, nous devons utiliser une approche diffรฉrente pour afficher les รฉlรฉments de la pile. L'objet (obj) est une variable temporaire, dรฉclarรฉe pour contenir chaque รฉlรฉment de la pile. Nous utilisons ensuite l'instruction foreach pour parcourir chaque รฉlรฉment de la pile. Pour chaque รฉlรฉment de pile, la valeur est attribuรฉe ร  la variable obj. Nous utilisons ensuite la commande Console.Writeline pour afficher la valeur sur la console.
  4. Nous utilisons la propriรฉtรฉ Count (st.count) pour obtenir le nombre d'รฉlรฉments dans la pile. Cette propriรฉtรฉ renverra un numรฉro. Nous affichons ensuite cette valeur ร  la console.
  5. Nous utilisons ensuite la mรฉthode Contains pour voir si la valeur 3 est prรฉsente dans notre pile. Cela renverra une valeur vraie ou fausse. Nous affichons ensuite cette valeur de retour ร  la console.

Si le code ci-dessus est entrรฉ correctement et que le programme est exรฉcutรฉ, la sortie suivante sera affichรฉe.

Sortie :

Pile en C#

ร€ partir du rรฉsultat, nous pouvons voir que les รฉlรฉments de la pile sont affichรฉs. De plus, la valeur True est affichรฉe pour indiquer que la valeur 3 est dรฉfinie sur la pile.

Note: Vous avez remarquรฉ que le dernier รฉlรฉment poussรฉ sur la pile est affichรฉ en premier. Il s'agit de l'รฉlรฉment le plus haut de la pile. Le nombre d'รฉlรฉments de pile est รฉgalement affichรฉ dans la sortie.

Exemple 2 : mรฉthode Stack.Pop()

Examinons maintenant la fonctionnalitรฉ ยซ supprimer ยป. Nous verrons le code requis pour supprimer l'รฉlรฉment le plus haut de la pile.

Pile en C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Stack st = new Stack();
   st.Push(1);
   st.Push(2);
   st.Push(3);
   
   st.Pop();

   foreach (Object obj in st)
   {
    Console.WriteLine(obj);
   }
    Console.ReadKey();
  }
 }
}

Code Explication:-

  1. Ici, nous รฉmettons simplement la mรฉthode pop qui est utilisรฉe pour supprimer un รฉlรฉment de la pile.

Si le code ci-dessus est saisi correctement et que le programme est exรฉcutรฉ, la sortie suivante sera affichรฉe.

Sortie :

Pile en C#

On voit que l'รฉlรฉment 3 a รฉtรฉ supprimรฉ de la pile.

C# Stack Peek() Method

The Push and Pop methods work with the top of the stack, but sometimes you only need to look at the top element without removing it. The Peek method does exactly that. It returns the topmost value of the stack while leaving the collection unchanged, which is useful when you want to test the next item before deciding to pop it.

ร‰tape 1) Create a stack and push three elements onto it, so the value 3 sits on top.

ร‰tape 2) Call the Peek method to read the top element, then check the Count property to confirm nothing was removed.

using System;
using System.Collections;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Stack st = new Stack();
   st.Push(1);
   st.Push(2);
   st.Push(3);
   Console.WriteLine(st.Peek());
   Console.WriteLine(st.Count);
   Console.ReadKey();
  }
 }
}

Code Explication:-

  1. A stack named st is declared, and the values 1, 2, and 3 are added with the Push method, so 3 becomes the topmost element.
  2. The Peek method returns the top element without removing it, and the Count property still reports the full number of items in the stack.

When the program runs, it prints the value 3 from Peek and then the count 3, which proves the element stays on the stack. If the stack is empty, Peek throws an InvalidOperationException, so it is safe to check Count before calling it.

Generic Stack<T> in C#

The examples above use the non-generic Stack class from System.Collections, which stores every element as an object. Modern C# code usually prefers the generic Stack<T> class from the System.Collections.Generic namespace. It binds the stack to a single declared type, so the compiler checks every Push and Pop and no casting or boxing is needed.

The key benefits of the generic Stack<T> are listed below.

  • Sรฉcuritรฉ du type : The type is fixed at declaration, so only values of that type can be pushed, and errors are caught at compile time.
  • No boxing: Value types such as int are stored directly, which avoids the boxing cost that the non-generic Stack pays.
  • Cleaner reads: Pop and Peek return the declared type directly, so you do not cast the result back from object.
using System;
using System.Collections.Generic;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Stack<string> st = new Stack<string>();
   st.Push("Java");
   st.Push("Python");
   Console.WriteLine(st.Pop());
   Console.ReadKey();
  }
 }
}

In this example the stack is declared as Stack<string>, so it accepts only string values. The Pop method returns a string directly and prints Python, the last value pushed. For any new project, the generic Stack<T> is the recommended choice.

Difference Between Stack and Queue in C#

A stack and a file are both collections that control the order in which elements are removed, but they use opposite rules. A stack is last in, first out, while a queue is first in, first out. Choosing the right one makes the intent of your code clear to other developers.

Les principales diffรฉrences sont รฉnumรฉrรฉes ci-dessous :

  • Commande: A stack removes the most recently added element first (LIFO), while a queue removes the oldest element first (FIFO).
  • Mรฉthodologie: A stack uses Push and Pop, whereas a queue uses Enqueue to add and Dequeue to remove.
  • Top-element access: A stack reads its next item with Peek, and a queue reads its next item with Peek from the front.
  • Utilisations typiques: Stacks fit undo features, expression evaluation, and recursion tracking, while queues fit scheduling, buffering, and breadth-first traversal.

Both types are available in generic form as Stack<T> and Queue<T> in System.Collections.Generic, so you gain type safety with either choice.

FAQ

Calling Pop or Peek on an empty stack throws an InvalidOperationException. Check the Count property first, or use the generic Stack methods TryPop and TryPeek, which return false instead of throwing when the stack holds no elements.

Push and Pop both run in constant O(1) time because they only touch the top of the stack. When the internal array must grow, an occasional Push resizes it, but the average cost per operation stays constant.

No. A stack exposes only its top through Peek and Pop, so it has no index accessor like a list. To read every value, enumerate the stack with a foreach loop or copy it using the ToArray method.

The Clear method removes every element from the stack in one call and resets Count to zero. To remove items one at a time from the top instead, call Pop in a loop until Count reaches zero.

The standard Stack class is not thread-safe for writes when several threads change it at once. For concurrent access, use ConcurrentStack from System.Collections.Concurrent, which offers atomic TryPush and TryPop methods without external locks.

Call the ToArray method to copy the stack into a new array, ordered from top to bottom. You can also pass the stack to a List constructor to build a generic list while keeping le mรชme ordre.

Yes. GitHub Copilot writes Stack declarations, Push and Pop calls, and foreach loops from a short comment or method name. It frequently suggests the generic Stack version, since that is the recommended collection for new C# code.

Stacks rarely store ML.NET training data, which flows through typed collections and the IDataView pipeline. However, the LIFO stack concept appears inside machine learning algorithms for backtracking, depth-first search, and managing recursive method calls.

Rรฉsumez cet article avec :