zoukankan      html  css  js  c++  java
  • 链队列之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;
    }
  • 相关阅读:
    【响应式Web设计实践 #BOOK#】
    【JS】(+﹏+)~
    -_-#【邮件】qq邮箱不显示图片
    -_-#【Markdown】
    51Nod——N1284 2 3 5 7的倍数
    51Nod——N1118 机器人走方格
    洛谷——P1014 Cantor表
    洛谷—— P1434 滑雪
    洛谷——P1443 马的遍历
    python(24)- 面向对象进阶
  • 原文地址:https://www.cnblogs.com/james1207/p/3293784.html
Copyright © 2011-2022 走看看