📄 tstack.h
字号:
//: C16:TStack.h
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Stack using templates
#ifndef TSTACK_H_
#define TSTACK_H_
// Declaration required:
template<class T> class TStackIterator;
template<class T> class TStack {
public: //////////// BC++ 5.3 bug hack??
struct link {
T* data;
link* next;
link(T* Data, link* Next) {
data = Data;
next = Next;
}
} * head;
int owns;
public:
TStack(int Owns = 1) : head(0), owns(Owns) {}
~TStack();
void push(T* Data) {
head = new link(Data,head);
}
T* peek() const { return head->data; }
T* pop();
int Owns() const { return owns; }
void Owns(int newownership) {
owns = newownership;
}
friend class TStackIterator<T>;
};
template<class T> T* TStack<T>::pop() {
if(head == 0) return 0;
T* result = head->data;
link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}
template<class T> TStack<T>::~TStack() {
link* cursor = head;
while(head) {
cursor = cursor->next;
// Conditional cleanup of data:
if(owns) delete head->data;
delete head;
head = cursor;
}
}
template<class T> class TStackIterator {
TStack<T>::link* p;
public:
TStackIterator(const TStack<T>& tl)
: p(tl.head) {}
TStackIterator(const TStackIterator& tl)
: p(tl.p) {}
// operator++ returns boolean indicating end:
int operator++() {
if(p->next)
p = p->next;
else p = 0; // Indicates end of list
return int(p);
}
int operator++(int) { return operator++(); }
// Smart pointer:
T* operator->() const {
if(!p) return 0;
return p->data;
}
T* current() const {
if(!p) return 0;
return p->data;
}
// int conversion for conditional test:
operator int() const { return p ? 1 : 0; }
};
#endif // TSTACK_H_ ///:~
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -