栈:
#pragma once
//template<class T>//静态
//class Stack
//{
//protected:
// T _a[N];
// size_t _top;//但是这种定义方式不好
//};
//动态
template<class T>
class Stack
{
public:
Stack()
:_a(NULL)
, _size(0)
, _capacity(0)
{}
~Stack()
{
if (_a)
{
delete[]_a;
_capacity = _size = 0;
}
}
bool Empty()
{
return _size == 0;
}
size_t Size()
{
return _size;
}
void Push(const T& x)
{
CheckCapacity();
_a[_size++] = x;
}
void Pop()
{
assert(_size > 0);
--_size;
}
T& Top()
{
assert(_size > 0);
return _a[_size - 1];
}
void CheckCapacity()
{
if (_size >= _capacity)
{
_capacity = _capacity == 0 ? 3 : _capacity * 2;//开新空间
T* tmp = new T[_capacity];
for (size_t i = 0; i < _size; ++i)//拷数据
{
tmp[i] = _a[i];
}
delete[]_a;
_a = tmp;//再指向数据
}
}
protected:
T* _a;
size_t _size;
size_t _capacity;
};
void TestStack()
{
Stack<int>s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
while (!s1.Empty())
{
cout << s1.Top() << " ";
s1.Pop();
}
cout << endl;
}
队列:
#pragma once
template<class T>
struct QueueNode
{
T _data;
QueueNode<T>* _next;
QueueNode(const T& x)
:_next(NULL)
, _data(x)
{}
};
template<class T>
class Queue
{
typedef QueueNode<T> Node;
public:
Queue()
:_head(NULL)
, _tail(NULL)
{}
void Push(const T& x)
{
if (_tail == NULL)
{
_head = _tail = new Node(x);
}
else
{
_tail->_next = new Node(x);
_tail = _tail->_next;
}
}
void Pop()
{
if (_head)
{
Node* next = _head->_next;
delete _head;
_head = next;
}
}
T& Front()
{
assert(_head);
return _head->_data;
}
size_t Size()
{
Node*cur = _head;
size_t n = 0;
while (cur)
{
++n;
cur = cur->_next;
}
return n;
}
bool Empty()
{
return -_head == NULL;
}
protected:
Node* _head;
Node* _tail;
};
void TestQueue()
{
Queue<int> q;
q.Push(1);
q.Push(2);
q.Push(3);
q.Push(4);
while (!q.Empty())
{
cout << q.Front() << " ";
q.Pop();
}
cout << endl;
//while (q.Size() > 0)//q.Size()可以改进,这里的时间复杂度为O(N^2)
//{
// cout << q.Front() << " ";
// q.Pop();
//}
//cout << endl;
}