栈
什么是栈?
栈(stack)是限定仅在表尾进行插入和删除操作的线性表
我们把允许插入和删除的一端称为栈顶(Top),另一端称为栈底(bottom),不含任何数据原色的栈称为空栈。栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构。
实现一个栈
代码实现:
template <class T>
class stack
{
public:
stack()
:_data(NULL)
, _size(0)
, _capacity(0)
{}
stack(const stack<T>& s)
{
_data = new T[s._size];
for (size_t i = 0; i < s._size; ++i)
{
_data[i] = s._data[i];
}
_size = s._size;
_capacity = s._capacity;
}
~stack()
{
if (_data)
{
delete[] _data;
_data = NULL;
_size = 0;
_capacity = 0;
}
}
void CheckCapacity()
{
if (_size == _capacity)
{
size_t _newCapacity = _capacity * 2 + 3;
T* tmp = new T[_newCapacity];
assert(tmp);
for (size_t i = 0; i < _size; ++i)
{
tmp[i] = _data[i];
}
delete[] _data;
_data = tmp;
_capacity = _newCapacity;
}
}
void Push(const T& x)
{
if (_size == _capacity)
{
CheckCapacity();
}
_data[_size] = x;
_size++;
}
void Pop()
{
assert(_size);
--_size;
}
T& Top()
{
return _data[_size-1];
}
bool Empty()
{
return (_size == 0);
}
private:
T* _data;
size_t _size;
size_t _capacity;
};
测试用例:
void Test1()
{
stack<int> mystack;
mystack.Push(1);
mystack.Push(2);
mystack.Push(3);
mystack.Push(4);
mystack.Pop();
mystack.Pop();
mystack.Pop();
while (!mystack.Empty())
{
cout << mystack.Top() << ' ';
mystack.Pop();
}
cout << endl;
}
实现结果:
队列
什么是队列?
队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。
队列是一种先进先出(First In First Out)的线性表,简称FIFO。我们将允许插入的一端称为队尾,允许删除的一端称为队头。
实现一个队列
代码实现:
template<class T>
struct ListNode
{
T _data;
ListNode* _next;
ListNode(const T& x)
:_data(x)
, _next(NULL)
{}
};
template<class T>
class queue
{
typedef ListNode<T> Node;
public:
queue()
{
_head = new Node(T());//匿名对象
_head->_next = NULL;
}
queue(const queue<T>& q)
{
Node* cur = q._head;
while (cur)
{
Push(cur->_data);
cur = cur->_next;
}
}
~queue()
{
Node* cur = _head;
while (cur)
{
Node* tmp = cur;
cur = cur->_next;
delete tmp;
}
_head = NULL;
}
void Push(const T& x)
{
Node* tmp = new Node(x);
Node* cur = _head;
while (cur->_next)
{
cur = cur->_next;
}
cur->_next = tmp;
tmp->_next = NULL;
}
void Pop()
{
Node* cur = _head->_next;
Node* tmp = cur;
_head->_next = tmp->_next;
delete tmp;
}
T& Back()
{
Node* cur = _head;
while (cur->_next)
{
cur = cur->_next;
}
return cur->_data;
}
T& Front()
{
return _head->_next->_data;
}
bool Empty()
{
return (_head->_next == NULL);
}
void Print()
{
Node* cur = _head->_next;
while (cur)
{
cout << cur->_data << ' ';
cur = cur->_next;
}
cout << endl;
}
private:
Node* _head;
};
测试用例:
void Test2()
{
queue<int> myqueue;
myqueue.Push(1);
myqueue.Push(2);
myqueue.Push(3);
myqueue.Push(4);
myqueue.Push(5);
myqueue.Push(6);
myqueue.Print();
while (!myqueue.Empty())
{
cout << myqueue.Front() << ' ';
myqueue.Pop();
}
cout << endl;
myqueue.Push(1);
myqueue.Push(2);
myqueue.Push(3);
myqueue.Push(4);
myqueue.Push(5);
myqueue.Push(6);
myqueue.Pop();
myqueue.Pop();
myqueue.Pop();
myqueue.Print();
cout << myqueue.Front() << ' ';
cout << endl;
cout << myqueue.Back() << ' ';
cout << endl;
}
实现结果: