// Stack名字空间
namespace Stack
{
using System; public class Stack
{
private Node first = null;
private int count = 0;
public bool Empty
{
get
{
return (first == null);
}
}
public int Count
{
get
{
return count;
}
}
public object Pop()
{
if (first == null)
{
throw new InvalidOperationException("Cant pop from an empty stack");
}
else
{
object temp = first.Value;
first = first.Next;//这里的Next为什么会自动到下一个,
count--;
return temp;
}
}
public void Push(object o)
{
first = new Node(o, first);//这里只是个构造函数,对联Next,Value进行了初始化
count++;
}
class Node
{
public Node Next;
public object Value;//这时原类型为什么要声明为object 类型,Node类型或其它类型不行吗? public Node(object value) : this(value, null) { } public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
} class StackApp
{
static void Main()
{
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;
}
}
}
namespace Stack
{
using System; public class Stack
{
private Node first = null;
private int count = 0;
public bool Empty
{
get
{
return (first == null);
}
}
public int Count
{
get
{
return count;
}
}
public object Pop()
{
if (first == null)
{
throw new InvalidOperationException("Cant pop from an empty stack");
}
else
{
object temp = first.Value;
first = first.Next;//这里的Next为什么会自动到下一个,
count--;
return temp;
}
}
public void Push(object o)
{
first = new Node(o, first);//这里只是个构造函数,对联Next,Value进行了初始化
count++;
}
class Node
{
public Node Next;
public object Value;//这时原类型为什么要声明为object 类型,Node类型或其它类型不行吗? public Node(object value) : this(value, null) { } public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
} class StackApp
{
static void Main()
{
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;
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货