数据结构:模板实现栈和队列

(一)模板实现栈

#pragma once
typedef unsigned int size_t;
template <class T>
class Stack
{
public:
 Stack()
  :_array(NULL)
  ,_top(-1)
  ,_capacity(0)
 {}
 ~Stack()
 {
  if(_array)
  {
   delete[] _array;
  }
 }
public:
 void Push(const T& num)
 {
  _CheckCapacity();
  _array[++_top] = num;
 }
 void Pop()
 {
  if(Empty())
  {
   printf("Empty!");
  }
  else
  {
   _top--;
  }
 }
 T& GetTop()
 {
  return _array[_top];
 }
 void PrintStack()
 {
  cout<<array[_top];
 }
 size_t Size()
 {
  return _top + 1;
 }
 bool Empty()
 {
  return _top == -1;
 }
private:
 void _CheckCapacity()
 {
  if(_array == NULL)
  {
   _capacity = 3;
   _array = new T[_capacity];
   return;
  }
  if(_capacity = _top + 1)
  {
   _capacity *= 2;
   T* tmp = new T[_capacity];
   for(size_t i = 0; i <=(int)_top; i++)
   {
    tmp[i] = _array[i];
   }
   _array = tmp;
  }
 }
private:
 T* _array;
 int _top;                 //下标
 size_t _capacity;
};

2.模板实现队列

#pragma once
template <class T>
struct Node
{
 T _data;
 Node<T>* _next;
 Node(const T& d)
  :_data(d)
  ,_next(NULL);
 {}
};
template <class T>
class Queue
{
public:
 Queue()
  :_head(NULL)
  ,_tail(NULL)
  ,_size(0)
 {}
 ~Queue
 {
  if(_head)
   delete _head;
  if(_tail)
   delete _tail;
 }
public:
 void Push(const T& d)
 {
  if(_head == NULL)
  {
   _head = _tail = new Node<T>(d);
  }
  else
  {
   _tail->_next = new Node<T>(d);
   _tail = _tail->_next;
  }
  _size++;
 }
 void Pop()
 {
  if(_head == NULL)
  {
   cout<<"Empty!"<<endl;
   return;
  }
  else if(_head == _tail)
  {
   delete _head;
   _head = _tail = NULL;
  }
  else
  {
   Node<T>* tmp = _head;
   _head = _head->_next;
   delete tmp;
  }
  _size--;
 }
 bool Empty()
 {
  return _head == NULL;
 }
 size_t Size()
 {
  return _size;
 }
 T& Front()
 {
  assert(_head);
  return _head->_data;
 }
 T& Back()
 {
  assert(_tail);
  return _tail->_data;
 }
private:
 Node<T>* _head;
 Node<T>* _tail;
 size_t _size;
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值