Stack

In this chapter you will learn:

  1. Generic Stack and non-generic Stack

Generic Stack and non-generic Stack

Stack<T> and Stack are last-in first-out (LIFO) data structures, providing methods to Push and Pop.

The generic Stack has the following methods:

public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable
{//j  a  v a  2 s  .com
    public Stack();
    public Stack (IEnumerable<T> collection); // Copies existing elements 
    public Stack (int capacity);  // Lessens auto-resizing 
    public void Clear();
    public bool Contains (T item);
    public void CopyTo (T[] array, int arrayIndex);
    public int Count { get; }
    public Enumerator<T> GetEnumerator(); // To support foreach 
    public T Peek();
    public T Pop();
    public void Push (T item); 
    public T[] ToArray(); 
    public void TrimExcess();
}

The following example demonstrates Stack<int>.

using System;//from j ava2  s  .c o  m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Sample
{
    public static void Main()
    {
        var s = new Stack<int>();
        s.Push(1);  //  Stack = 1 
        s.Push(2);  //  Stack = 1,2 
        s.Push(3);  //  Stack = 1,2,3
        Console.WriteLine(s.Count); 
        Console.WriteLine(s.Peek());
        Console.WriteLine(s.Pop()); 
        Console.WriteLine(s.Pop()); 
        Console.WriteLine(s.Pop()); 
        Console.WriteLine (s.Pop());  

    }

}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Clone an ArrayList
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack