在 C# 中將堆疊複製到陣列
若要將堆疊複製到陣列,程式碼如下 −
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
stack.Push(60);
stack.Push(70);
stack.Push(80);
stack.Push(90);
stack.Push(100);
Console.WriteLine("Displaying the stack...");
foreach(int val in stack){
Console.WriteLine(val);
}
int[] intArr = new int[stack.Count];
stack.CopyTo(intArr, 0);
Console.WriteLine("Displaying the array...");
foreach(int val in intArr){
Console.WriteLine(val);
}
}
}輸出
這將產生以下輸出 −
Displaying the stack... 100 90 80 70 60 50 40 30 20 10 Displaying the array... 100 90 80 70 60 50 40 30 20 10
示例
現在讓我們去看另一個示例 −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);
Console.WriteLine("Displaying the stack...");
foreach(int val in stack){
Console.WriteLine(val);
}
int[] intArr = new int[10];
stack.CopyTo(intArr, 2);
Console.WriteLine("Displaying the array...");
foreach(int val in intArr){
Console.WriteLine(val);
}
}
}輸出
這將產生以下輸出 −
Displaying the stack... 50 40 30 20 10 Displaying the array... 0 0 50 40 30 20 10 0 0 0
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP