using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication15
{
class MyStack //自定义的栈
{
private int count;
private int index; //定位标识
ArrayList arr; //声明,ArrayList可以动态改变大小,里面元素类型为object
public MyStack()
{
arr = new ArrayList(); //分配相应内存
this.index = -1;
}
public int getCount //查看栈中元素个数
{
get
{
return this.arr.Count;
}
}
public object pop() //出栈
{
object o = arr[index];
arr.RemoveAt(index);
index--;
return o;
}
public void push(object o) //进栈
{
arr.Add(o);
index++;
}
public object peek() //查看栈顶元素
{
return arr[index];
}
public void clear() //清空栈
{
arr.Clear();
index = -1;
}
}
class Program
{
static void Main(string[] args)
{
MyStack stack = new MyStack();
Console.WriteLine("执行进栈操作");
stack.push(1);
stack.push(2);
stack.push(3);
Console.WriteLine("进栈操作结束");
Console.WriteLine("栈顶元素为:{0}",stack.peek());
Console.WriteLine("栈中元素共有:{0}个",stack.getCount);
Console.WriteLine("执行出栈操作:");
while (stack.getCount > 0)
{
Console.WriteLine(stack.pop());
}
Console.WriteLine("出栈操作后,栈中元素共有:{0}个",stack.getCount);
Console.Read();
}
}
}
实现栈类
最新推荐文章于 2022-10-05 17:16:27 发布