| 发表于:2007-03-30 20:30:43 楼主 |
using system; namespace ysp18 { public class stack { //first 栈顶 private node first=null; //count 栈中节点数 private int count=0; //栈空属性 提供get访问器 public bool empty { get { return(first==null); } } //计数属性,提供get访问器 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; count--; return temp; } } //入栈 public void push(object o) { first=new node(o,first); count++; } //定义节点类 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; } } } public class stackapp { public static void main(string[] args) { stack s = new stack(); if (s.empty) { console.writeline( "栈为空! "); } else { console.writeline( "栈为非空! "); } //压入栈5个节点 for (int i = 0; i < 5; i++) { s.push(i); } console.writeline( "往栈中压入了{0}个元素 ",s.count); //全部出栈 for (int j = 0; j < s.count; j++) { console.writeline( "弹出了第{0}个元素,还剩{0}个元素 ",(int)s.pop()+1,s.count); s = null; } } } } |
|
|
|
|