📜  带有示例的C#堆栈

📅  最后修改于: 2021-05-29 19:19:14             🧑  作者: Mango

堆栈用于表示对象的后进先出集合。当您需要对项目进行后进先出访问时,可以使用它。它具有通用和非通用的集合类型。泛型堆栈在System.Collections.Generic命名空间中定义,而非泛型堆栈在System.Collections命名空间下定义,这里我们将讨论非泛型类型栈。根据程序的需要,使用堆栈来创建不断增长的动态集合。在堆栈中,可以存储相同类型或不同类型的元素。

下图说明了Stack类的层次结构:

重要事项:

  • Stack类实现IEnumerableICollectionICloneable接口。
  • 在列表中添加项目时,称为推动元素。
  • 删除它时,这称为弹出元素。
  • 堆栈的容量是堆栈可以容纳的元素数量。将元素添加到堆栈后,容量会根据需要通过重新分配自动增加。
  • 在堆栈中,允许您存储重复的元素。
  • 堆栈接受null作为引用类型的有效值。

如何创建堆栈?

堆栈类具有三个用于创建堆栈的构造函数,如下所示:

  • Stack():此构造函数用于创建Stack类的实例,该实例为空并具有默认初始容量。
  • Stack(ICollection):此构造函数用于创建Stack类的实例,该实例包含从指定集合中复制的元素,并且具有与复制的元素数量相同的初始容量。
  • Stack(Int32):此构造函数用于创建Stack类的实例,该实例为空并具有指定的初始容量或默认初始容量(以较大者为准)。

让我们看看如何使用Stack()构造函数创建一个堆栈:
步骤1:借助using关键字,在程序中包含System.Collections命名空间。

using System.Collections;

步骤2:使用Stack类创建一个堆栈,如下所示:

Stack stack_name = new Stack();

步骤3:如果要在堆栈中添加元素,请使用Push()方法在堆栈中添加元素。如下例所示。

例子:

C#
// C# program to illustrate how to
// create a stack
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push('G');
        my_stack.Push(null);
        my_stack.Push(1234);
        my_stack.Push(490.98);
 
        // Accessing the elements
        // of my_stack Stack
        // Using foreach loop
        foreach(var elem in my_stack)
        {
            Console.WriteLine(elem);
        }
    }
}


C#
// C# program to illustrate how to
// remove elements from the stack
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        Console.WriteLine("Total elements present in"+
                    " my_stack: {0}", my_stack.Count);
                                                     
        my_stack.Pop();
 
        // After Pop method
        Console.WriteLine("Total elements present in "+
                      "my_stack: {0}", my_stack.Count);
 
                                                    
        // Remove all the elements
        // from the stack
        my_stack.Clear();
 
        // After Pop method
        Console.WriteLine("Total elements present in "+
                      "my_stack: {0}", my_stack.Count);
                                                    
    }
}


C#
// C# program to illustrate how to
// get topmost elements of the stack
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        Console.WriteLine("Total elements present in"+
                     " my_stack: {0}",my_stack.Count);
                                                    
        // Obtain the topmost element
        // of my_stack Using Pop method
        Console.WriteLine("Topmost element of my_stack"
                          + " is: {0}",my_stack.Pop());
                           
        Console.WriteLine("Total elements present in"+
                    " my_stack: {0}", my_stack.Count);
                          
        // Obtain the topmost element
        // of my_stack Using Peek method
        Console.WriteLine("Topmost element of my_stack "+
                              "is: {0}",my_stack.Peek());
                           
 
        Console.WriteLine("Total elements present "+
                 "in my_stack: {0}",my_stack.Count);
                           
    }
}


C#
// C# program to illustrate how
// to check element present in
// the stack or not
using System;
using System.Collections;
 
class GFG {
 
    // Main  Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        // Checking if the element is
        // present in the Stack or not
        if (my_stack.Contains("GeeksforGeeks") == true)
        {
            Console.WriteLine("Element is found...!!");
        }
 
        else
        {
            Console.WriteLine("Element is not found...!!");
        }
    }
}


输出:
490.98
1234

G
geeksforgeeks
Geeks


如何从堆栈中删除元素?

在堆栈中,允许您从堆栈中删除元素。 Stack类提供了两种不同的方法来删除元素,并且这些方法是:

  • 清除此方法用于从堆栈中删除所有对象。
  • Pop 此方法删除堆栈的开始元素。

例子:

C#

// C# program to illustrate how to
// remove elements from the stack
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        Console.WriteLine("Total elements present in"+
                    " my_stack: {0}", my_stack.Count);
                                                     
        my_stack.Pop();
 
        // After Pop method
        Console.WriteLine("Total elements present in "+
                      "my_stack: {0}", my_stack.Count);
 
                                                    
        // Remove all the elements
        // from the stack
        my_stack.Clear();
 
        // After Pop method
        Console.WriteLine("Total elements present in "+
                      "my_stack: {0}", my_stack.Count);
                                                    
    }
}
输出:
Total elements present in my_stack: 4
Total elements present in my_stack: 3
Total elements present in my_stack: 0


如何获得堆栈的最高元素?

在Stack中,可以使用Stack类提供的以下方法轻松地找到堆栈的最顶层元素:

  • Pop 此方法通过修改返回堆栈的开始处的对象,这意味着该方法将删除堆栈中最顶层的元素。
  • 偷看此方法在不删除对象的情况下将其返回到堆栈的开头。

例子:

C#

// C# program to illustrate how to
// get topmost elements of the stack
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        Console.WriteLine("Total elements present in"+
                     " my_stack: {0}",my_stack.Count);
                                                    
        // Obtain the topmost element
        // of my_stack Using Pop method
        Console.WriteLine("Topmost element of my_stack"
                          + " is: {0}",my_stack.Pop());
                           
        Console.WriteLine("Total elements present in"+
                    " my_stack: {0}", my_stack.Count);
                          
        // Obtain the topmost element
        // of my_stack Using Peek method
        Console.WriteLine("Topmost element of my_stack "+
                              "is: {0}",my_stack.Peek());
                           
 
        Console.WriteLine("Total elements present "+
                 "in my_stack: {0}",my_stack.Count);
                           
    }
}
输出:
Total elements present in my_stack: 4
Topmost element of my_stack is: GeeksforGeeks
Total elements present in my_stack: 3
Topmost element of my_stack is: geeks23
Total elements present in my_stack: 3


如何检查堆栈中元素的可用性?

在堆栈中,可以使用Contain()方法检查给定元素是否存在。换句话说,如果要搜索给定堆栈中的元素,请使用Contains()方法。如果元素存在于堆栈中,则此方法返回true。否则,返回false。

例子:

C#

// C# program to illustrate how
// to check element present in
// the stack or not
using System;
using System.Collections;
 
class GFG {
 
    // Main  Method
    static public void Main()
    {
 
        // Create a stack
        // Using Stack class
        Stack my_stack = new Stack();
 
        // Adding elements in the Stack
        // Using Push method
        my_stack.Push("Geeks");
        my_stack.Push("geeksforgeeks");
        my_stack.Push("geeks23");
        my_stack.Push("GeeksforGeeks");
 
        // Checking if the element is
        // present in the Stack or not
        if (my_stack.Contains("GeeksforGeeks") == true)
        {
            Console.WriteLine("Element is found...!!");
        }
 
        else
        {
            Console.WriteLine("Element is not found...!!");
        }
    }
}
输出:
Element is found...!!


通用堆栈与非通用堆栈

Generic Stack

Non-Generic Stack

Generic stack is defined under System.Collections.Generic namespace. Non-Generic stack is defined under System.Collections namespace.
Generic stack can only store same type of elements. Non-Generic stack can store same type or different types of elements.
There is a need to define the type of the elements in the stack. There is no need to define the type of the elements in the stack.
It is type-safe. It is not type-safe.