程序代码:
//queue.h
#ifndef _QUQUE_H_
#define _QUEUE_H_
#include <stdbool.h>
#define MAXQUEUE 10
typedef int Item;
typedef struct node{
Item item;
struct node *next;
}Node;
typedef struct queue {
Node *fornt;
Node *arer;
int items;
}QUEUE;
void InitializeQueue(QUEUE *pq);
bool QueueIsEmpty(const QUEUE *pq);
bool QueueIsFull(const QUEUE *pq);
unsigned int QueueIsCount(const QUEUE *pq);
bool EN_Queue(QUEUE *pq, Item item);
bool DE_Queue(Item *pitem, QUEUE *pq);
void EmptyTheQueue(QUEUE *pq);
#endif
程序代码:
//queue.c
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
static void CopyToNode(Item item, Node *pq);
static void CopyToItem(Item *item, Node *pq);
void InitializeQueue(QUEUE *pq)
{
pq->fornt = pq->arer = NULL;
pq->items = 0;
}
bool QueueIsEmpty(const QUEUE *pq)
{
return (pq->items == 0);
}
bool QueueIsFull(const QUEUE *pq)
{
return (pq->items == MAXQUEUE);
}
unsigned int QueueIsCount(const QUEUE *pq)
{
return (pq->items);
}
bool EN_Queue(QUEUE *pq, Item item)
{
Node *pnew;
if (QueueIsFull(pq))
return false;
pnew = (Node*)malloc(sizeof(Node));
if (pnew == NULL)
return false;
CopyToNode(item, pnew);
pnew->next = NULL;
if (QueueIsEmpty(pq))
pq->fornt = pnew;
else
pq->arer->next = pnew;
pq->arer = pnew;
pq->items++;
return true;
}
bool DE_Queue(Item *pitem, QUEUE *pq)
{
Node *pnew;
if (QueueIsEmpty(pq))
return false;
//CopyToItem(pitem ,pq->fornt);
pnew = pq->fornt;
pq->fornt = pq->fornt->next;
free(pnew);
pq->items--;
if (pq->items == 0)
pq->arer = NULL;
return true;
}
void EmptyTheQueue(QUEUE *pq)
{
Item dummy;
while (!QueueIsEmpty(pq))
DE_Queue(&dummy, pq);
}
static void CopyToNode(Item item, Node *pq)
{
pq->item = item;
}
static void CopyToItem(Item *item, Node *pq)
{
*item = pq->item;
}
程序代码:
//Driver.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
char getchoise(void);
int main(int argc, char *argv[])
{
Item temp;
QUEUE list;
char ch;
puts("a> add . b> delete ");
InitializeQueue(&list);
while ((ch = getchoise()) != 'q')
{
while (ch != 'a' && ch != 'b')
continue;
if (ch == 'a')
{
puts("input number .");
scanf("%d", &temp);
while (getchar() != '\n')
continue;
if (!QueueIsFull(&list))
{
EN_Queue(&list, temp);
printf("putting %d into queue", temp);
printf("%d items in queue." ,QueueIsCount(&list));
}
else
{
puts("Queue is full!");
}
}
else
{
if (QueueIsEmpty(&list))
puts("Nothing to delete");
else
{
DE_Queue(&temp, &list);
printf("Removeing %d from queue" ,temp);
}
}
printf("%d item in queue.",QueueIsCount(&list));
puts("Type a to add number b to delete q to quite");
}
EmptyTheQueue(&list);
puts("Done!");
return 0;
}
char getchoise(void)
{
char ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}