C#实现栈
using System;
using System.Collections.Generic;
using System.Text;
namespace Stack
{
public class Stack
{
private Node first = null;
private int count = 0;
public bool Empty
{
get
{
return (first == null);
}
}
public int Count
{
get
{
return count;
}
}
//Push
public void Push(object o)
{
first = new Node(o,first);
count++;
}
//Pop
public object Pop()
{
if (first == null)
{
throw new InvalidOperationException("Can't Pop from an empty stack.");
}
else
{
object temp = first.Value;
first = first.Next;
count--;
return temp;
}
}
}
class Node
{
public Node Next;
public object Value;
public Node(object value) : this(value, null) { }
public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
class StackApp
{
static void Main(string[] args)
{
Stack s = new Stack();
if (s.Empty) Console.WriteLine("堆栈为空。");
else Console.WriteLine("堆栈非空。");
for (int i = 0; i < 5; i++)
{
s.Push(i);
}
Console.WriteLine("往堆栈中压入了{0}个元素。",s.Count);
for (int i = 0; i < 5; i++)
{
Console.WriteLine("弹出第{0}个元素,还剩{1}个元素。",(int)s.Pop()+1,s.Count);
}
s = null;
Console.ReadKey();
}
}
}