(一)静态队列
数据结构:
typedef struct Node
{
int date;
struct Node *next;
}Node, *PNode;
typedef struct queue
{
PNode top;
PNode bottom;
}Queue, *PQueue;
(1)初始化
void InitQueue(Queue *queue)
{
queue->top = 0;
queue->bottom = 0;
}
(2)入栈
void Push(Queue *queue, int date)
{
if ((queue->top + 1) % MAXSIZE == queue->bottom)
{
cout << "队列已满!" << endl;
return;
}
queue->elem[queue->top] = date;
queue->top = (queue->top +1)% MAXSIZE;
}
(2)出栈
void Pop(Queue * queue, int *date)
{
if (queue->top == queue->bottom)
{
cout << "队列为空!" << endl;
return;
}
(*date) = queue->elem[queue->bottom];
queue->bottom = (queue->bottom + 1) % MAXSIZE;
}
(二)动态队列
(1)初始化
void InitQueue(PQueue pHead)
{
pHead->top = NULL;
pHead->bottom = NULL;
}
(2)入栈
void Push(PQueue pQueue,int date)
{
PNode pNew= new Node;
if (!pNew)
{
cout << "进队失败!" << endl;
return;
}
pNew->date = date;
pNew->next = NULL;
if ( IsEmpty(pQueue))
{
pQueue->top = pQueue->bottom = pNew;
}
else
{
pQueue->top->next = pNew;
pQueue->top = pNew;
}
}
(3)出栈
void Pop(PQueue pQueue, int *date)
{
if (IsEmpty(pQueue))
{
cout << "出队失败,队列为空!" << endl;
return;
}
if (pQueue->bottom == pQueue->top)
{
PNode p = pQueue->bottom;
(*date) = pQueue->bottom->date;
pQueue->bottom = pQueue->top = NULL;
delete p;
}
else
{
(*date) = pQueue->bottom->date;
PNode p = pQueue->bottom;
pQueue->bottom = pQueue->bottom->next;
delete p;
}
}
(4)判栈空
bool IsEmpty(PQueue pQueue)
{
return pQueue->top == NULL&&pQueue->bottom == NULL;
}