Queue(FIFO):先进先出
尾添加,头弹出。
功能函数:
Init()
Push()
Pop()
IsEmpty()
用链表实现队列:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int value;
struct node* pNext;
}Myqueue;
typedef struct queue
{
int nCount;
Myqueue* pHead;
Myqueue* pTail;
}Queue;
void Init(Queue**pqueue)
{
*pqueue = (Queue*)malloc(sizeof(Queue));
(*pqueue)->nCount = 0;
(*pqueue)->pHead = NULL;
(*pqueue)->pTail = NULL;
}
void Push(Queue*pqueue,int num)
{
if(pqueue == NULL)
{
printf("队列不存在!\n");
exit(1);
}
Myqueue* pTemp = (Myqueue*)malloc(sizeof(Myqueue));
pTemp->value = num;
pTemp->pNext = NULL;
if(pqueue->pHead == NULL)
{
pqueue->pHead = pTemp;
}
else
{
pqueue->pTail->pNext = pTemp;
}
pqueue->pTail = pTemp;
pqueue->nCount++;
}
int Pop(Queue*pqueue)
{
if(pqueue == NULL)
{
printf("队列不存在!\n");
exit(1);
}
if(pqueue->nCount == 0)return -1;
Myqueue*Del = pqueue->pHead;
int nNum = Del->value;
pqueue->pHead = pqueue->pHead->pNext;
free(Del);
Del = NULL;
pqueue->nCount--;
return nNum;
}
int IsEmpty(Queue*pqueue)
{
if(pqueue == NULL)
{
printf("队列不存在!\n");
exit(1);
}
return pqueue->nCount == 0?1:0;
}
int main()
{
Queue* pqueue = NULL;
Init(&pqueue);
Push(pqueue,1);
Push(pqueue,2);
Push(pqueue,3);
printf("%d\n",Pop(pqueue));
printf("%d\n",Pop(pqueue));
printf("%d\n",Pop(pqueue));
printf("%d\n",IsEmpty(pqueue));
return 0;
}