链堆栈的实现

代码
 
    
//链堆栈的接口定义如下所示。
    public interface IStack<T>
    {
        
int GetLength(); //求栈的长度
        bool IsEmpty(); //判断栈是否为空
        void Clear(); //清空操作
        void Push(T item); //入栈操作
        T Pop(); //出栈操作
        T GetTop(); //取栈顶元素
    }
   
//链堆栈方法的实现
   public class LinkStack<T> : IStack<T>
    {
        
private Node<T> top; //栈顶指示器
        private int num; //栈中结点的个数
        
//栈顶指示器属性
        public Node<T> Top
        {
            
get
            {
                
return top;
            }
            
set
            {
                top 
= value;
            }
        }
        
//元素个数属性
        public int Num
        {
            
get
            {
                
return num;
            }
            
set
            {
                num 
= value;
            }
        }

        
//构造器
        public LinkStack()
        {
            top 
= null;
            num 
= 0;
        }
        
//求链栈的长度
        public int GetLength()
        {
            
return num;
        }
        
//清空链栈
        public void Clear()
        {
            top 
= null;
            num 
= 0;
        }
        
//判断链栈是否为空
        public bool IsEmpty()
        {
            
if ((top == null&& (num == 0))
            {
                
return true;
            }
            
else
            {
                
return false;
            }
        }
        
//入栈
        public void Push(T item)
        {
            Node
<T> q = new Node<T>(item);
            
if (top == null)
            {
                top 
= q;
            }
            
else
            {
                q.Next 
= top;
                top 
= q;
            }
            
++num;
        }
        
//出栈
        public T Pop()
        {
            
if (IsEmpty())
            {
                Console.WriteLine(
"Stack is empty!");
                
return default(T);
            }
            Node
<T> p = top;
            top 
= top.Next;
            
--num;
            
return p.Data;
        }
        
//获取栈顶结点的值
        public T GetTop()
        {
            
if (IsEmpty())
            {
                Console.WriteLine(
"Stack is empty!");
                
return default(T);
            }
            
return top.Data;
        }
    }

 

posted @ 2010-04-07 15:19  Blue Sky ......  阅读(276)  评论(0编辑  收藏  举报