选择显示字体大小

数据结构学习(c++)之栈和队列

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


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

  栈的定义和实现

#ifndef stack_h
#define stack_h
#include "list.h"

template <class type> class stack : list<type>//栈类定义
{
 public:
  void push(type value)
  {
   insert(value);
  }

 type pop()
 {
  type p = *getnext();
  removeafter();
  return p;
 }

 type gettop()
 {
  return *getnext();
 }

 list<type> ::makeempty;
 list<type> ::isempty;

};

#endif

  队列的定义和实现

#ifndef queue_h
#define queue_h
#include "list.h"

template <class type> class queue : list<type>//队列定义
{
 public:
  void enqueue(const type &value)
  {
   lastinsert(value);
  }

 type dequeue()
 {
  type p = *getnext();
  removeafter();
  isempty();
  return p;
 }

 type getfront()
 {
  return *getnext();
 }

 list<type> ::makeempty;
 list<type> ::isempty;

};
#endif

  测试程序

#ifndef stacktest_h
#define stacktest_h
#include "stack.h"

void stacktest_int()
{
 cout << endl << "整型栈测试" << endl;
 cout << endl << "构造一个空栈" << endl;
 stack<int> a;
 cout << "将1~20入栈,然后再出栈" << endl;
 for (int i = 1; i <= 20; i++) a.push(i);
  while (!a.isempty()) cout << a.pop() << ' ';
  cout << endl;
}
#endif

#ifndef queuetest_h
#define queuetest_h
#include "queue.h"

void queuetest_int()
{
 cout << endl << "整型队列测试" << endl;
 cout << endl << "构造一个空队列" << endl;
 queue<int> a;
 cout << "将1~20入队,然后再出队" << endl;
 for (int i = 1; i <= 20; i++) a.enqueue(i);
 while (!a.isempty()) cout << a.dequeue() << ' ';
 cout << endl;
}
#endif

  没什么好说的,你可以清楚的看到,在单链表的基础上,栈和队列的实现是如此的简单。


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons