#include<maloc.h>
//定义队列
typedef struct node
{
int data;
struct node *next;
}Queue;
typedef struct pointer
{
Queue *front; //队首
Queue *rear; //队尾
}QPointer;
//初始化队列
void QueueInit(QPointer *qp)
{
Queue *que;
que = (Queue *)malloc(sizeof(Queue));
//队首和队尾指向同一个内存空间,指针域为NULL
que->next = NULL;
qp->front = que;
qp->rear = que;
}
//判断队列是否为空
int IsEmpty(QPointer *qp)
{
//队首和队尾指针是否相同
if(qp->front == qp->rear)
{
return 1;
}
return 0;
}
//插入元素到队列
int QueuePush(QPointer *qp , int element)
{
Queue *que;
que = (Queue *)malloc(sizeof(Queue));
if(que == NULL)
{
return 0;
}
que->data = element;
que->next = NULL;
qp->rear->next = que; //节点插入队尾
qp->rear=que; //调整队尾指针
return 0;
}
//删除数据元素
int QueuePop(QPointer *qp , int *element)
{
Queue *que;
if(IsEmpty(qp))
{
return 0;
}
que = qp->front->next;
*element = que->data; //出队元素
qp->front->next = que->next;
//判断是不是只剩下最后一个元素
if(qp->rear == que)
{
qp->rear = qp->front;
}
free(que);
return 1;
}
int main(int argc, char *argv[])
{
QPointer *qp;
int x;
qp = (QPointer *)malloc(sizeof(QPointer));
QueueInit(qp);
printf("input positive integers:\n");
scanf("%d" , &x);
while(x > 0)
{
QueuePush(qp , x);
scanf("%d",&x);
}
Queue *p = qp->front->next;
if(p == NULL)
{
return 0;
}
printf("queue element:\n");
while(p)
{
printf("%d" , p->data);
p=p->next;
}
printf("\n");
printf("delete:\n");
while(QueuePop(qp , &x))
{
printf("%d" , x);
}
printf("\n");
p = qp->front;
free(p);
free(qp);
return 0;
}
C/C++代码(1):队列
最新推荐文章于 2024-07-24 18:11:53 发布