链栈的实现

本文介绍了一种使用链表实现队列的方法,并提供了完整的C++代码实现。文章详细解释了链式队列的基本操作,包括入队、出队、获取队首元素及判断队列是否为空等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件:


#ifndef linkqueue_h
#define linkqueue_h
struct Node
{
int data;
Node * next;
};
class linkqueue
{
public:
linkqueue();
void input(int x);
void gettop();
void output();
void empty();
private:
Node *front,*rear;
};


#endif




函数定义;


#include"头文件.h"
#include<iostream>
using namespace std;
linkqueue::linkqueue()
{
Node * s=NULL;
s=new Node;
s->next=NULL;
front=rear=s;
}


void linkqueue::input(int x)
{
Node *s=NULL;
s=new Node;
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
}


void linkqueue::gettop()
{
if(front!=rear)
cout<<"队头数据是:"<<front->next->data<<endl;
}


void linkqueue::output()
{
if(rear==front)throw"下溢";
Node *s=NULL;
int x;
x=front->next->data;
s=front->next;
front->next=s->next;
if(s->next==NULL) rear=front;
delete s;
cout<<"出队的数据是:"<<x<<endl;
}


void linkqueue::empty()
{
if(rear==front)
cout<<"队为空"<<endl;
else
cout<<"队非空"<<endl;
}



main函数;


#include"头文件.h"
#include<iostream>
using namespace std;


void main()
{
linkqueue L;
int x[100];
int b;
cout<<"请输入要入队的数据个数:";
cin>>b;
cout<<"请输入要入队的数据:";
for(int a=0;a<b;a++)
{
cin>>x[a];
L.input(x[a]);
}
L.gettop();
y: int c;
cout<<"请输入要出队的数据个数:";
cin>>c;
if(c>b)
{
cout<<"出队的数据个数大于队现有的个数,请重新输入";
goto y;
}
else
{
for(int d=0;d<c;d++)
L.output();
}
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值