C# 堆栈 - Push() 方法
C# 堆栈的 Push() 方法用于在堆栈顶部插入对象或元素。当计数等于容量时,堆栈的容量会通过自动重新分配内部数组来增加,并在插入新元素之前将旧元素转移到新数组中。
如果计数小于堆栈容量,则 push 操作复杂度为 O(1)。如果需要增加容量才能插入新元素,则 push 操作复杂度为 O(n)。其中 n 是元素的数量或计数。
语法
以下是 C# 堆栈 Push() 方法的语法 -
public virtual void Push (object obj);
参数
此方法接受一个对象作为参数,其中对象表示推送到堆栈的元素。它可以为 null -
返回值
此方法不返回任何值。
示例 1:在 Stack<int> 中使用 Push 方法
以下是使用 Push() 方法将元素插入堆栈的基本示例 -
using System;
using System.Collections.Generic;
class Example {
static void Main() {
Stack<int> numbers = new Stack<int>();
// 插入元素
numbers.Push(10);
numbers.Push(20);
numbers.Push(30);
Console.WriteLine("Stack after Push operations:");
foreach (int num in numbers) {
Console.WriteLine(num);
}
}
}
输出
以下是输出 -
Stack after Push operations: 30 20 10
示例 2:在 Stack<string> 中使用 Push 方法
让我们看另一个使用 Push() 方法在堆栈中插入字符串元素的示例 -
using System;
using System.Collections.Generic;
class Example {
static void Main() {
Stack<string> words = new Stack<string>();
words.Push("Hello");
words.Push("World");
words.Push("C#");
Console.WriteLine("Stack after Push operations:");
foreach (string word in words) {
Console.WriteLine(word);
}
}
}
输出
以下是输出 -
Stack after Push operations: C# World Hello
示例 3:使用 Push 方法在堆栈中存储混合数据类型
以下示例使用 push() 方法在堆栈中存储不同类型的元素 -
using System;
using System.Collections;
class Example {
static void Main() {
Stack myStack = new Stack();
myStack.Push(100);
myStack.Push("C#");
myStack.Push(3.14);
myStack.Push(true);
Console.WriteLine("Stack after Push operations:");
foreach (var item in myStack) {
Console.WriteLine(item);
}
}
}
输出
以下是输出 -
Stack after Push operations: True 3.14 C# 100
示例 4:使用 Push 方法在堆栈中存储混合数据类型
在此示例中,我们使用 Push 方法在堆栈中存储自定义对象 -
using System;
using System.Collections.Generic;
class Person {
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) {
Name = name;
Age = age;
}
public override string ToString() {
return $"Name: {Name}, Age: {Age}";
}
}
class Example {
static void Main() {
Stack<Person> people = new Stack<Person>();
people.Push(new Person("Aman", 25));
people.Push(new Person("Gupta", 24));
people.Push(new Person("Vivek", 26));
Console.WriteLine("Stack after Push operations:");
foreach (var person in people) {
Console.WriteLine(person);
}
}
}
输出
以下是输出 -
Stack after Push operations: Name: Vivek, Age: 26 Name: Gupta, Age: 24 Name: Aman, Age: 25

csharp_stack.html