栈和队列

#pragma once


#include <stack>


template<class T>
class Stack
{
public:
Stack()
:_a(NULL)
,_size(0)
,_capacity(0)
{}


~Stack()
{
if (_a)
{
delete [] _a;
_capacity = _size = 0;
}
}


void Push(const T& x)
{
CheckCapcity();


_a[_size++] = x;
}


void Pop()
{
assert(_size > 0);
--_size;
}


T& Top()
{
assert(_size > 0);
return _a[_size-1];
}


void CheckCapcity()
{
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;
}
}


bool Empty()
{
return _size == 0;
}


size_t Size()
{
return _size;
}


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;


stack<int> st1;
st1.push(1);
st1.push(2);
st1.push(3);
st1.push(4);


while (!st1.empty())
{
cout<<st1.top()<<" ";
st1.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()
{
size_t n = 0;
Node* cur = _head;
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值