/*
#include<iostream>
#include<assert.h>
using namespace std;
template<class T>
class Stack
{
private:
T* _pdata;
size_t _size;
size_t _capacity;
public:
Stack()
:_pdata(NULL)
, _size(0)
, _capacity(0)
{}
~Stack()
{
if (_pdata != 0)
{
delete _pdata;
_pdata = NULL;
}
_size = 0;
_capacity = 0;
}
bool empty()
{
if (size == 0)
return 0;
}
size_t size()
{
return _size;
}
T& top()
{
assert(_size);
return _pdata[size - 1];
}
void capacityIsFull()
{
if (_size == _capacity)
{
size_t new_capacity = _capacity * 2 + 3;
T* temp = new T[new_capacity];
for (int i = 0; i < _size; i++)
{
temp[i] = _pdata[i];
}
delete _pdata;
_pdata = temp;
_capacity = new_capacity;
}
}
void push(const T& data)
{
capacityIsFull();
_pdata[_size] = data;
++_size;
}
void pop()
{
if (!empty())
{
_size--;
}
else
{
cout << "栈已空" << endl;
}
}
}
void FunTest()
{
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
cout << "Stack.size" << s.size() << endl;
cout << "Stack.top" << s.top() << endl;
s.pop();
cout << "Stack.size" << s.size() << endl;
cout << "Stack.top" << s.top() << endl;
s.pop();
cout << "Stack.size" << s.size() << endl;
cout << "Stack.top" << s.top() << endl;
}
int main()
{
FunTest();
return 0;
}
*/
#include<iostream>
using namespace std;
template<class T>
struct QueueNode
{
T _data;
QueueNode<T>* _next;
QueueNode(const T& data)
:_data(data)
, _next(NULL)
{}
};
template<class T>
class Queue
{
private:
Node* _front;
Node* _rear;
size_t _size;
public:
typrdef QueueNode<T> Node;
Queue()
:_front(NULL)
, _rear(NULL)
, _size(0)
{}
~Queue()
{
if (_front)
{
Node* del = _front;
_front = _front->_next;
delete del;
del = NULL;
}
}
bool empty()
{
if (!_front)
return 0;
}
size_t size()
{
return _size;
}
T& front()
{
return _front->_data;
}
void push(const T& data)//尾插
{
if (empty())
{
Node* newnode = new Node(data);
_front = _rear = data;
++_size;
}
else
{
Node* newnode = new Node(data);
_rear->_next = newnode;
_rear = _rear->_next;
++_size;
}
}
void pop()//头删
{
if (empty())
cout << "栈已空" << endl;
else
{
Node* del = _front;
_front = _front->_next;
delete del;
del == NULL;
}
}
};
void FunTest()
{
Queue<int>s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout << "size" << s.size() << endl;
cout << "front" << s.front() << endl;
s.pop();
cout << "size" << s.size() << endl;
cout << "front" << s.front() << endl;
}
int main()
{
FunTest();
return 0;
}
栈和队列
最新推荐文章于 2024-07-22 09:43:39 发布