zoukankan      html  css  js  c++  java
  • 栈是一种特殊的线性表,主要是先进后出。

    主要函数包括:压栈、出栈、清空栈、栈长度

    主要代码如下:

    #include <iostream>
    using namespace std;
    
    template<class T>
    class sstackNode
    {
    public:
    	sstackNode(){next=0;}
    	T data;
    	sstackNode<T> *next;
    };
    
    template <class T>
    class Mystack
    {
    public:
    	Mystack();//初始化
    	unsigned int MystackLength();//返回栈的长度
    	void push(T x);//入栈
    	void pop();//出栈
    	T top();//获取栈顶数据
    	void clear();//清空栈
    	bool isEmpty();//判断是否为空
    private:
    protected:
    	unsigned int stacklength;
    	sstackNode <T> *node;
    	sstackNode <T> *headnode;
    };
    template <class T>
    Mystack<T>::Mystack()//初始化
    {
    	stacklength	=0;
    	headnode=NULL;
    }
    template <class T>
    unsigned int Mystack<T>::MystackLength()//返回栈的长度
    {
    	return stacklength;
    }
    
    template <class T>
    void Mystack<T>::push(T x)//入栈
    {
    	node=new sstackNode<T>();
    	node->data=x;
    	if (headnode==NULL)
    	{
    		node->next=NULL;
    	}
    	else
    	{
    		node->next=headnode;
    	}
    	headnode=node;
    	stacklength++;
    }
    
    template <class T>
    void Mystack<T>::pop()//出栈
    {
    	if (headnode==NULL)
    	{
    		return;
    	}
    	else
    	{
    		if (headnode->next=NULL)
    		{
    			delete(headnode);
    			headnode=NULL;
    		}
    		else
    		{
    			node=headnode;
    			headnode=node->next;
    			delete(node);	
    			node=NULL;
    		}
    		stacklength--;
    	}
    }
    
    template <class T>
    T Mystack<T>::top()//获取栈顶数据
    {
    	return(headnode->data);
    }
    
    template <class T>
    void Mystack<T>::clear()//清空栈
    {
    	if (headnode==NULL)
    	{
    		return;
    	}
    	while(headnode!=NULL)
    	{
    		node=headnode;
    		headnode=headnode->next;
    		delete(node);
    		node=NULL;
    	}
    	stacklength=0;
    }
    
    template <class T>
    bool Mystack<T>::isEmpty()//判断是否为空
    {
    	if (0==stacklength)
    	{
    		return true;
    	}
    	else
    		return false;
    }
    

      

  • 相关阅读:
    xmind 8 readme
    【08】英语词汇速记大全1词根词缀记忆法
    【20180312】2018年03月12日(随想)
    大佬说
    github私有库购买信息
    【01】用构造器创建函数中的小知识
    【01】魔芋使用MDN的一点点经验
    10.12 telnet:远程登录主机
    10.11 arping:发送arp请求
    10.10 traceroute:追踪数据传输路由状况
  • 原文地址:https://www.cnblogs.com/lanye/p/3240403.html
Copyright © 2011-2022 走看看