• 链队列之C++实现


                链队列时建立在单链表的基础之上的。由于是动态分配节点内存,所以无需判满。

              链队列的形式如下:

    1、队列空

    2、队列存在数据

             下面介绍下C++实现的链队列,VC6下调试通过。

    1、文件组织

    2、lq.h链队列类的说明

    #ifndef _LQ_H_
    #define _LQ_H_
    
    typedef int dataType;
    
    struct node                 //队列节点
    {
    	dataType data;          //数据域
    	node *next;             //指针域
    };
    
    class lq
    {
    public:
    	lq();                     //构造函数
    	~lq();                    //析构函数
    	void push(dataType var);  //入队
    	void pop();               //出队
    	dataType front();         //取对头元素,对头不变化
    	bool isEmpty();           //判空.head=tail=NULL时队列为空
    
    private:
    	node *head;               //对头指针
    	node *tail;               //队尾指针
    };
    
    #endif


    3、lq.cpp链队列的定义

    #include <iostream>
    #include "lq.h"
    using namespace std;
    
    lq::lq()
    {
    	head = NULL;           //head=tail=NULL时队列为空
    	tail = NULL;
    }
    
    lq::~lq()
    {
    	node *ptr = NULL;
    
    	while(head != NULL)
    	{
    		ptr = head->next;
    		delete head;
    		head = ptr;
    	}
    }
    
    void lq::push(dataType var)
    {
    	node *ptr = new node;
    
    	ptr->data = var;
    	ptr->next = NULL;
    	if(tail != NULL)         
    	{
    		tail->next = ptr;       //不是入队的第一个节点
    	}
    	else
    	{
    		head = ptr;				//如果是入队的第一个节点
    	}
    	tail = ptr;
    }
    
    void lq::pop()
    {
    	node *ptr = head->next;
    
    	delete head;
    	head = ptr;
    
    	if(head == NULL)         //head时要将tail也赋为NULL
    	{
    		tail = NULL;
    	}
    }
    
    dataType lq::front()
    {
    	return head->data;
    }
    
    bool lq::isEmpty()
    {
    	return head == NULL && tail == NULL;
    }
    


    4、main.cpp

    #include <iostream>
    #include "lq.h"
    using namespace std;
    
    int main()
    {
    	lq exp;
    	int i =0;
    
    	for(i=0;i<100;i++)
    	{
    		exp.push(i);
    	}
    
    	for(i=0;i<200;i++)
    	{
    		if(!exp.isEmpty())
    		{
    			cout<<exp.front()<<endl;
    			exp.pop();
    		}
    	}
    
    	if(exp.isEmpty())
    	{
    		cout<<"队列为空!"<<endl;
    	}
    
    	return 0;
    }
  • 相关阅读:
    python学习-基础-day5-文件操作和函数
    (转) 什么是立即执行函数?有什么作用?
    AngularJS 从DOM中获取scope
    AngularJS中Directive指令系列
    AngularJS中Directive指令系列
    angularJS ng-repeat中的directive 动态加载template
    (转) 前端面试之js相关问题(一)
    ES6 localStorage 类库
    underscore.js 源码分析5 基础函数和each函数的使用
    记录使用jQuery和Python抓取采集数据的一个实例
  • 原文地址:https://www.cnblogs.com/james1207/p/3293784.html
Copyright © 2020-2023  润新知