Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication2.cpp : 定義主控台應用程式的進入點。
- //
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- template<class T, int MaxSize = 20>
- class Stack
- {
- public:
- void init(){ sp = 0, sp2 = 0; }
- void push(T data);
- T pop();
- private:
- int sp, sp2;
- T buffer[MaxSize];
- static void Error(){ cout << "\nStack Error\n"; }
- };
- template < class T, int MaxSize>
- void Stack<T, MaxSize>::push(T data)
- {
- if (sp == MaxSize)
- Error();
- else
- buffer[sp++] = data;
- }
- template<class T,int MaxSize>
- T Stack<T, MaxSize>::pop()
- {
- if (sp == 0)
- {
- Error();
- return 0;
- }
- return buffer[--sp];
- }
- template<class T, int MaxSize = 20>
- class Queue
- {
- public:
- void init(){ sp = 0, sp2 = 0; }
- void push(T data);
- T pop();
- private:
- int sp, sp2;
- T buffer[MaxSize];
- static void Error(){ cout << "\nStack Error\n"; }
- };
- template < class T, int MaxSize>
- void Queue<T, MaxSize>::push(T data)
- {
- if (sp == MaxSize)
- Error();
- else
- buffer[sp++] = data;
- }
- template<class T, int MaxSize>
- T Queue<T, MaxSize>::pop()
- {
- if (sp2 == sp)
- {
- Error();
- return 0;
- }
- return buffer[sp2++];
- }
- int main()
- {
- Queue<int> st1;
- Queue<char, 10> st2;
- st1.init();
- st2.init();
- st1.push(1); st1.push(2); st1.push(3);
- st2.push('a'); st2.push('b'); st2.push('c');
- cout << st1.pop();
- cout << st2.pop();
- cout << st1.pop();
- cout << st2.pop();
- cout << st1.pop();
- cout << st2.pop();
- cout << st1.pop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement