队列可以用数组和链表实现

队列是先入先出额数据结构,它的实现可以用数组,也可以用链表。

1. 数组实现队列

用数组实现链表时,需要预先分配数组的大小,用front和rear下标分别表示队头元素下标和队尾元素下标,插入一个元素时,使队尾的下标rear加1,删除一个元素时,front下标加1,判断是否为空的队列只要判断front和rear是否相等。队列的插入操作可表示为

代码实现:

# include <stdio.h>  
# include <stdlib.h>  
# define Maxsize  100  
struct queue   
{  
    int front;  
    int rear;  
    int q[Maxsize];  
};  

int main()  
{     
    void initialqueue(queue*);  
    void push(queue *,int);  
    int pop(queue*);  
    int isempty(queue*);  
    int isfull(queue*);  
    queue p;  
    initialqueue(&p);  
    push(&p,1);  
    push(&p,2);  
    push(&p,3);  
    printf("%d\n",isempty(&p));  
    printf("%d\n",pop(&p));  

    system("pause");  
return 0;  
}  

void initialqueue(queue *p)  
{  
    p->front=p->rear=0;  
}  
int isfull(queue *p)  
{  
    return p->rear==p->front+Maxsize-1;  
}  

int isempty(queue *p)  
{  
    return p->front==p->rear;  
}  
void push(queue* p,int x)  
{  
if(isfull(p))  
{  
    printf("queue is full\n");  
    exit(-1);  
}  
p->q[p->rear++]=x;  
}  

int pop(queue *p)  
{  
if(isempty(p))  
{  
printf("queue is empty\n");  
exit(-1);  
}  
return p->q[p->front++];  

}  

2. 链表实现队列

用链表实现队列,需要定义节点结构体存储节点的值和指针,另外还要定义头指针和尾指针,分别指向队头和队尾,插入元素的操作可以表示为

# include <stdio.h>  
# include <stdlib.h>  
struct node  
{  
int num;  
node *next;  
};  
typedef struct   
{  
    node *front;  
    node *rear;  
}link;  
int main()  
{  
    void initialqueue(link p);  
    link push(link,int);  
    int pop(link);  
    int isempty(link);  
    int isfull(link);  
    link p={0,0};  
    initialqueue(p);  
    p=push(p,1);  
    p=push(p,2);  
    p=push(p,3);  
    printf("%d\n",pop(p));  
    system("pause");  
return 0;  
}  

void initialqueue(link p)  
{  
p.front=p.rear=0;  
}  
int isempty(link p)  
{  
    return p.front==NULL&&p.rear==NULL;  
}  

link push(link p,int x)  
{  
    node *t=(node *)malloc(sizeof(node));  
    t->num=x;  
    t->next=NULL;  
if(isempty(p))  
{  
    p.front=p.rear=t;     
}  
else  
{  
    p.rear->next=t;    
    p.rear=t;  
}  
return p;  
}  

int pop(link p)  
{  
    int temp;  
    node *t;  
if(isempty(p))  
{  
printf("queue is empty\n");  
exit(-1);  
}  
if(p.front!=p.rear){  
temp=p.front->num;  
t=p.front;  
p.front=p.front->next;  
free(t);  
}  
else  
{  
temp=p.front->num;  
t=p.front;  
p.front=p.rear=NULL;  
free(t);  
}  
return temp;  
}  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhisheng_blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值