C++之链队列

一、学习要点:
1.链队列的实现不用限制队列的长度;当删除元素时,只需要改变头结点指向的首元结点(phead->next=phead->next->next),插入只改变尾节点的(pnode为新插入结点,pend->next=pnode;pend=pnode,即可)
2.头结点,首元结点,尾节点有不明白的可参考我的上一篇博客。
3.总体来说,链队列的实现比数组队列的实现要方便,而且实用。
4.结构体里面也可以有构造器;
5.第一个元素一定是插在初始化的pend->next;所以在初始化的时候一定要让phead=pend,达到让phead指向首元元素的目的。
6.c++中取反用!;不是~,切记切记切记;
二、代码:
demo092103.cpp

#include<iostream>
#include<stdlib.h>
using namespace
template<class T>
struct Node{
	Node(T t):value(0),next(nullptr){};
	Node();
	T value;
	Node<T>* next;
}
template<class T>
class Linkqueque{
public:
	Linkqueque();
	~Linkqueque();
	bool isEmpty();
	int size();
	void push(T t);
	bool pop();
	T front();
private:
	Node<T>* phead;
	Node<T>*pend;
	int count;
};
Linkqueque<T>::Linkqueque(){
	//此处一定要有phead=pend,因为插入是插在pend的next里,故第一个元素一定在pend->next;因为第一个元素一定在初始化的pend后面,所以初始化的时候一定有phead=pend;让phead指向第一个元素,即首元元素
	Node<T>* phead=new Node<T>();
	pend=phead;
	count=0;
}
template<class T>
Linkqueque<T>::~Linkqueque(){
	while(pend->next!=nullptr){
		Node<T>* pnode=new Node<T>();
		pnode=pend->next;
		phead=pend->next;
		delete pnode;
	}
}
template<class T>
void Linkqueque<T>::push<T t>{
	Node<T>*  pnode=new Node<T>(t);
	pend->next=pnode;
	pend=pnode;
	count++;
}
template<class T>
bool Linkqueque<T>::pop(){	
	if(count==0){
	return false;
	}else{
	Node<T>* pnode;
	pnode=phead->next;
	phead->next=phead->next->next;
	delete pnode;
	count--;
	return true;
	}
}
template<class T>
bool Linkqueque<T>::isEmpty(){
return count==0;
}
template<class T>
int Linkqueque<T>::size(){
return count;
}
template<class T>
T Linkqueque<T>::front(){
return (phead->next->vlaue);
}

主函数代码
main.cpp

#include<iostream>
#include<stdlib.h>
#include<string>
#include"demo092103.cpp"
using namespace std;
int main(){
 Linkqueque<string> lqueque;
 lqueque.push("one");
 lqueque.push("two");
 lqueque.push("three");
 lqueque.push("four");
 lqueque.push("five");
 cout<<"队列大小"<<lqueque.size()<<endl;
 while(!lqueque.isEmpty()){
  cout<<lqueque.front()<<endl;
  lqueque.pop();
 }
 system("pause");
 return 0;
}

三、运行结果:
在这里插入图片描述
四、如有错误,欢迎指出,一块交流学习;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值