zoukankan      html  css  js  c++  java
  • 顺序栈

    MyStack.h

    #ifndef _MYSTACK_H
    #define _MYSTACK_H 
    
    #include "MyUtil.h"
    
    template <typename T>
    class MyStack
    {
    public:
    	MyStack(int stackCapacity = 10);
    	~MyStack();
    	bool IsEmpty() const; // 判断是否空
    	T& Top() const; 	  // 取栈顶元素
    	void Push(const T& item); // 放进元素
    	void Pop(); // 删除元素
    
    private:
    	T* stack;
    	int top;
    	int capacity;
    	
    };
    
    template <typename T>
    void MyStack<T>::Pop()
    {
    	if(IsEmpty()) throw "Stack is empty, cannot delete";
    	stack[top--].~T();
    
    }
    
    template <typename T>
    inline bool MyStack<T>::IsEmpty() const
    {
    	return top == -1;
    }
    
    template <typename T>
    inline T& MyStack<T>::Top() const
    {
    	if(IsEmpty()) throw "Stack is empty";
    	return stack[top];
    }
    
    template <typename T>
    MyStack<T>::MyStack(int stackCapacity):capacity(stackCapacity)
    {
    	if (capacity < 1) throw "stack capacity must be > 0";
    	stack = new T[capacity];
    	top = -1; // 没有数据的时候
    	
    }
    
    template <typename T>
    MyStack<T>::~MyStack()
    {
    	delete[] stack;
    }
    
    template <typename T>
    void MyStack<T>::Push(const T& item)
    {
    	if(top == capacity-1)
    	{
    		ChangeSize1D(stack, capacity, 2*capacity);
    		capacity *= 2;
    	}
    	stack[++top] = item;
    }
    
    #endif
    

    MyUtil.h

    #ifndef _MYUTIL_H
    #define _MYUTIL_H
    
    #include <iostream>
    
    template <typename T>
    void ChangeSize1D(T* &a, const int oldSize, const int newSize);
    
    template <typename T>
    void ChangeSize1D(T* &a, const int oldSize, const int newSize)
    {
    	if(newSize < 0) throw "New length must be >= 0";
    
    	T* temp = new T[newSize];
    	int number = std::min(oldSize, newSize);
    	std::copy(a, a+number, temp);
    	delete[] a;
    	a = temp;
    }
    
    
    #endif
    

    main.cpp

    /*
    * author:起风了_Zoe
    * date:2020.04.07
    */
    
    #include <iostream>
    #include <string>
    #include "MyStack.h"
    
    using namespace std;
    
    class anything
    {
    
    };
    
    int main()
    {
    	MyStack<string> myStringStack;
    	MyStack<anything> angStack;
    	MyStack<int> st;
    	st.Push(20);
    	st.Push(22);
    	st.Push(24);
    	st.Push(26);
    	cout << st.Top() << endl;
    	st.Pop();
    	cout << st.Top() << endl;	
    	st.Pop();
    	cout << st.Top() << endl;	
    	st.Pop();
    	cout << st.Top() << endl;	
    	cout << "OK!!!" << endl;
    	return 0;
    }
    
  • 相关阅读:
    spark streaming 整合kafka(二)
    JAVA设计模式之动态代理
    使用org.apache.commons.cli包来设计JAVA命令行工具
    HTML教程
    Java InputStream和Reader
    Java IO
    程序员怎么把自己的招牌打出去?
    Java设计模式之单例模式
    JAVA NIO
    Java文件流字节流和字符流的区别
  • 原文地址:https://www.cnblogs.com/Wind-Flies/p/12656370.html
Copyright © 2011-2022 走看看