using System;
using System.Collections;
namespace Lesson2_Stack
{
class Program
{
static void Main(string[] args)
{
#region 知识点一 栈的本质
// stack(栈)是一个c#为我们封装好的类
//它的本质也是object[]数组,只是封装了特殊的存储规则
//Stack是栈存储容器,栈是一种先进后出的数据结构
//先存入的数据后获取,后存入的数据先获取
//栈是先进后出
#endregion
#region 知识点二 声明
Stack sta = new Stack();
#endregion
#region 知识点三 增删改查
#region 增
//入栈
sta.Push("1");
sta.Push(123);
sta.Push(true);
sta.Push(1.2f);
#endregion
#region 删
//出栈
//删除并返回 Stack 顶部的对象。
//public virtual object? Pop ();
Object item = sta.Pop();
Console.WriteLine(item);
item = sta.Pop();
Console.WriteLine(item);
#endregion
#region 改
//栈只能通过出栈入栈修改栈顶元素
//从 Stack 中移除所有对象。
//public virtual void Clear ();
sta.Clear();
//获取 Stack 中包含的元素数。
//public virtual int Count { get; }
Console.WriteLine(sta.Count);
sta.Push("Panzi");
#endregion
#region 查
//栈只能取出栈顶元素
//返回位于 Stack 顶部的对象但不将其移除。
//public virtual object? Peek ();
Object v = sta.Peek();
Console.WriteLine(v);
//确定某元素是否在 Stack 中。
//public virtual bool Contains (object? obj);
if (sta.Contains("1.2f"))
{
Console.WriteLine("Exits");
} else
{
Console.WriteLine("No Exits");
}
#endregion
#endregion
#region 知识点四 遍历
//1.使用foreach遍历
//从栈顶到栈底
foreach(Object ob in sta)
{
Console.WriteLine(ob);
}
//2.使用ToArray()方法
//将 Stack 复制到新数组中。
//public virtual object?[] ToArray ();
Object[] arry = sta.ToArray();
foreach(Object it in arry)
{
Console.WriteLine(it);
}
//3.循环出栈
while (sta.Count > 0)
{
Console.WriteLine(sta.Pop());
}
Console.WriteLine(sta.Count);
#endregion
#region 知识点五 装箱拆箱
//由于用万物之父来存储数据,自然存在装箱拆箱。
//当往其中进行值类型存储时就是在装箱
//当将值类型对象取出来转换使用时,就存在拆箱。
#endregion
}
}
}
### 练习题
#### 1.简述栈的存储规则
先进后出
#### 2.写一个方法,计算一个数的二进制数,使用栈存储并打印
public void Solution(int n)
{
Stack sta = new Stack();
while (n != 0)
{
sta.Push(n % 2);
n /= 2;
}
foreach(Object item in sta) {
Console.Write(item);
}
}