我有用C#编写的简单控制台应用程序。寻找使用Pop和Peek的方法和优势。
Stack<string> movies = new Stack<string>();
movies.Push("Fire & Dew");
movies.Push("Hang Break");
movies.Push("Naughty Monkey");
movies.Push("Sabotage");
Console.WriteLine("All Movies\n");
foreach (string movie in movies)
{
Console.WriteLine(movie);
}
答案 0 :(得分:0)
stack.Pop()
- 删除并返回堆栈顶部的对象。MSDN
stack.Peek()
- 返回堆栈顶部的对象而不删除它。MSDN
因此,如果您只需阅读堆栈顶部,则应使用Peek
如果您需要浏览整个堆栈,则应使用Pop
。
答案 1 :(得分:0)
Stack被称为后进先出集合,您可以从堆栈顶部添加或删除元素。添加称为推送项目的元素。 从堆栈中删除元素通常称为弹出项目。如何使用Stack类查看代码。
在下面的代码中我声明了Stack。为简单起见,我用包含它的标题的字符串表示每部电影。 我通过单独将项目推入堆栈来添加更多数据。 一些奇怪的原因,执行此操作的方法称为Push,执行该行代码后,有四部电影 在它上面。
//Sabotage
//Naughty Monkey
//Hang Break
//Fire & Dew
Stack<string> movies = new Stack<string>();
movies.Push("Fire & Dew");
movies.Push("Hang Break");
movies.Push("Naughty Monkey");
movies.Push("Sabotage");
//To display the data use foreach loop
//You will notice that the foreach loop has displayed
//the movies in the reverse order to the order I put them on.
Console.WriteLine("All Movies\n");
foreach (string movie in movies)
{
Console.WriteLine(movie);
}
// To access the top most string which is "Fire & Dew title"
//I can get it by Pop()
//Data will be lost using Pop() but if you do not want to
//lose data use Peek() instead
//try first
string topMovie = movies.Pop();
//try later
//string topMovie = movies.Peek();
Console.WriteLine($"\nTop Movie is:{topMovie}");
Console.WriteLine("\nAll Movies: After popping\n");
foreach (string movie in movies)
{
Console.WriteLine(movie);
}