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

     1 #include <iostream>
     2 #include <assert.h>
     3 
     4 using namespace std;
     5 
     6 template<class T>
     7 class STACK
     8 {
     9 public:
    10     STACK(int sz = 100):top(-1), maxLen(sz)
    11     {
    12         date = new T[sz];
    13         assert(date != NULL);
    14     }
    15     ~STACK(){delete []date;}
    16     void Push(const T& a);
    17     bool Pop(T& x);
    18     bool Top(T& x);
    19     bool Empty() const{return top == -1;}
    20     bool Full(){return top == maxLen-1;}
    21     int Size(){return top+1;}
    22     void Clear(){top = -1;}
    23     friend ostream& operator << (ostream& os, const STACK<T>& s)
    24     {
    25         for(int i = 0; i <= s.top; i++)
    26             os<<s.date[i]<<" ";
    27         return os;
    28     }
    29 private:
    30     T *date;
    31     int top;
    32     int maxLen;
    33     void overflow();
    34 };
    35 
    36 template<class T>
    37 bool STACK<T>::Top(T& x)
    38 {
    39     if(Empty())return false;
    40     x = date[top];
    41     return true;
    42 }
    43 
    44 template<class T>
    45 void STACK<T>::overflow()
    46 {
    47     T* newdate = new T[maxLen<<1];
    48     if(newdate == NULL)return;
    49     for(int i = 0; i <= top; i++)
    50         newdate[i] = date[i];
    51     maxLen <<= 1;
    52     delete []date;
    53     date = newdate;
    54 }
    55 
    56 template<class T>
    57 void STACK<T>::Push(const T& a)
    58 {
    59     if(Full())overflow();
    60     date[++top] = a;
    61 }
    62 
    63 template<class T>
    64 bool STACK<T>::Pop(T& x)
    65 {
    66     if(Empty())return false;
    67     x = date[top--];
    68     return true;
    69 }
    70 
    71 int main()
    72 {
    73     int tmp;
    74     STACK<int> s;
    75     for(int i = 0; i < 10; i++)
    76         s.Push(i);
    77     cout << s << endl;
    78     s.Pop(tmp);
    79     cout << s << endl;
    80     s.Top(tmp);
    81     cout << tmp << endl;
    82     return 0;
    83 }
  • 相关阅读:
    JavaScript 19 数组(二)
    JavaScript 19 数组(一)
    JavaScript 18 字符串(三)
    JavaScript 18 字符串(二)
    JavaScript 18 字符串(一)
    History 5 : Silk Roads / Mongols / Ottoman and Mughal Empires
    History : Pictures of History
    001 markdown基本语法
    c#知识结构图
    c#知识结构图
  • 原文地址:https://www.cnblogs.com/Penn000/p/5910989.html
Copyright © 2011-2022 走看看