今天,再次实现一下数据结构中的栈和队列
这次我们用的是C++实现栈和队列,用到了C++多态的一种特性:泛型编程--模板
关于模板这个知识点,我们之前讲过,这次就不多说了
Stack.h
#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
template<typename T>
class Stack
{
public:
Stack()
:_p(NULL)
, _size(0)
, _capacity(0)
{}
~Stack()
{
if (_p != NULL)
{
delete _p;
_p = NULL;
_size = _capacity = 0;
}
}
void Push(const T& t)
{
CheckCapacity();
_p[_size++] = t;
}
void Pop()
{
assert(_size);
--_size;
}
T& Top()
{
return _p[_size - 1];
}
const T& Top()const
{
return _p[size - 1];
}
size_t Size()
{
return _size;
}
bool Empty()
{
return _size == 0;
}
protected:
T *_p;
size_t _size;
size_t _capacity;
void CheckCapacity()
{
if (_size >= _capacity)
{
size_t NewCapacity = _capacity * 2 + 3;
T* tmp = new T[NewCapacity];
for (size_t idx = 0; idx < _capacity; ++idx)
{
tmp[idx] = _p[idx];
}
delete[] _p;
_p = tmp;
_capacity = NewCapacity;
}
}
};
Queue.h
#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
template<typename T>
struct QueueNode
{
T* _value;
QueueNode* next;
QueueNode(const T& t)
:_value((T*)t)
, next(NULL)
{}
};
template<typename T>
class Queue
{
typedef QueueNode<T> Node;
public:
Queue()
:_head(NULL)
, _tial(NULL)
{}
~Queue()
{
Node* cur = _head;
while (cur)
{
Node* del = cur;
cur = cur->next;
delete[] del;
del = NULL;
}
}
void Push(const T& t)
{
if (_head == NULL)
{
_head = new Node(t);
_tial = _head;
}
else
{
_tial->next = new Node(t);
_tial = _tial->next;
_tial->next = NULL;
}
}
void Pop()
{
assert(_head);
if (_head == _tial)
{
delete[] _head;
_head = _tial = NULL;
}
else
{
Node* del = _head;
_head = _head->next;
delete[] del;
del = NULL;
}
}
T& Front()
{
assert(_head);
return (T&)_head->_value;
}
const T& Front()const
{
assert(_head);
return _head->_value;
}
T& Back()
{
assert(_tial);
return _tial->_value;
}
const T& Back()const
{
assert(_tial);
return _tial->_value;
}
size_t Size()
{
size_t count = 0;
Node* cur = _head;
while (cur)
{
cur = cur->next;
count++;
}
return count;
}
bool Empty()
{
return _head == NULL;
}
protected:
Node*_head;
Node* _tial;
};
顺便再提一下函数调用的栈帧,它和我们的栈是有相似的地方的。
无论是一个多么复杂的递归程序,我们都可以用非递归实现;
简单的递归可以直接用循环,难一点的递归我们就可以用数据结构中的栈进行实现