设为首页 加入收藏

TOP

数据结构学习(C++)之栈和队列
2014-11-01 12:30:07 来源: 作者: 【 】 浏览:51
Tags:数据结构 学习 队列

  栈和队列是操作受限的线性表,好像每本讲数据结构的数都是这么说的。有些书按照这个思路给出了定义和实现;但是很遗憾,本文没有这样做,所以,有些书中的做法是重复建设,这或许可以用不是一个人写的这样的理由来开脱。


  顺序表示的栈和队列,必须预先分配空间,并且空间大小受限,使用起来限制比较多。而且,由于限定存取位置,顺序表示的随机存取的优点就没有了,所以,链式结构应该是首选。


  栈的定义和实现


  #ifndef Stack_H


  #define Stack_H


  #include "List.h"


  template class Stack : List //栈类定义


  {


  public:


  void Push(Type value)


  {


  Insert(value);


  }


  Type Pop()


  {


  Type p = *GetNext();


  RemoveAfter();


  return p;


  }


  Type GetTop()


  {


  return *GetNext();


  }


  List ::MakeEmpty;


  List ::IsEmpty;


  };


  #endif


  队列的定义和实现


  #ifndef Queue_H


  #define Queue_H


  #include "List.h"


  template class Queue : List //队列定义


  {


  public:


  void EnQueue(const Type &value)


  {


  LastInsert(value);


  }


  Type DeQueue()


  {


  Type p = *GetNext();


  RemoveAfter();


  IsEmpty();


  return p;


  }


  Type GetFront()


  {


  return *GetNext();


  }


  List ::MakeEmpty;


  List ::IsEmpty;


  };


  #endif


  测试程序


  #ifndef StackTest_H


  #define StackTest_H


  #include "Stack.h"


  void StackTest_int()


  {


  cout << endl << "整型栈测试" << endl;


  cout << endl << "构造一个空栈" << endl;


  Stack a;


  cout << "将1~20入栈,然后再出栈" << endl;


  for (int i = 1; i <= 20; i++) a.Push(i);


  while (!a.IsEmpty()) cout << a.Pop() << ' ';


  cout << endl;


  }


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++:声明为非成员函数的时机 下一篇c++利用构造函数实现大小写转换

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: