#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
//链队列,链队列实质上是单链表,为了操作方便,需要设置队头和队尾两个指针,并放在一个结构体内,
//采用带头结点的单链表,使得队空与非空具有同一结构形式。
//链队列中结点类型
struct node{
int data ;
struct node * next ;
};
//链队列类型
struct linkqueue{
struct node * _front , *_rear ;
};
//初始化链队列
void initlinkqueue(struct linkqueue * p){
p->_front = (struct node*)malloc(sizeof(struct node)) ;//产生一个头结点并将地址填入头指针域
p->_rear = p->_front ;
p->_front->next = NULL ;
}
//入队列算法,不会产生上溢,故可省略队满判断
void addlinkqueue(struct linkqueue * p , int x){
struct node * temp = (struct node*)malloc(sizeof(struct node)) ;
temp->data = x ;
temp->next = NULL ;
p->_rear->next = temp ;//新结点插入队尾
p->_rear = temp ;//修改队尾指针
}
//出队列算法,为了避免在只有一个元素结点与多结点时操作不一致需修改队尾指针,算法中删除的是
//头结点而不是第一个元素结点,让第一个元素结点作为删除后的头结点,这样在物理上尽管删除的是头结点
//,而在逻辑上达到了删除第一个元素结点的目的。
int outlinkqueue(struct linkqueue * p) {
if(p->_front == p->_rear)
return NULL ; //队列为空返回NULL
struct node * temp = p->_front ;
p->_front = p->_front->next ;
free(temp) ;
return p->_front->data ;//返回原第一个元素结点的值,它在新的队头结点中保存着
}
//读队头元素
int gethead(struct linkqueue *p){
if(p->_front == p->_rear)
return NULL ;
return p->_front->next->data ;
}
//判断队列空
int isempty(struct linkqueue * p){
if(p->_front == p->_rear)
return 1 ;
return 0 ;
}
int main(){
struct linkqueue *qu ;
initlinkqueue(qu) ;
for(int i = 1 ; i<= 9 ; i++){
addlinkqueue(qu , i) ;
}
while(!isempty(qu)){
cout<<"删除的队头元素: "<<outlinkqueue(qu) << endl;
}
return 0 ;
}
链对列初始化/入队列/出队列/判空
最新推荐文章于 2023-04-20 09:50:55 发布