|
2#
楼主 |
发表于 2008-12-10 10:56:31
|
只看该作者
回复 1# 的帖子
晕阿,居然没找到如何上传附件。就贴出源代码了
queue.h
#pragma c9x on
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stdbool.h>
#define MAXQUEUE 5
typedef int Item;
typedef struct node
{
Item item;
struct node *next;
}Node;
typedef struct queue
{
Node * front;
Node * rear;
int items;
}Queue;
void InitializeQueue(Queue *pq);
bool QueueIsFull (const Queue *pq);
bool QueueIsEmpty (const Queue *pq);
int QueueItemCount(const Queue *pq);
bool EnQueue(Item item,Queue *pq);
bool DeQueue(Item *pitem, Queue *pq);
void EmputyTheQueue(Queue *pq);
#endif
queue.c 源代码
#include <stdio.h>
#include <stdlib.h>
#include <mcheck.h>
#include "queue.h"
static void CopyToNode (Item item, Node *pn);
static void CopyToItem (Node *pn, Item *pi);
void InitializeQueue(Queue *pq)
{
pq -> front = pq ->rear = NULL;
pq ->items = 0;
}
bool QueueIsFull (const Queue *pq)
{
return pq ->items == MAXQUEUE;
}
bool QueueIsEmpty(const Queue *pq)
{
return pq->items == 0;
}
int QueueItemCount(const Queue *pq)
{
return pq ->items;
}
bool EnQueue(Item item, Queue *pq)
{
Node *pnew;
if(QueueIsFull(pq))
return false;
pnew = (Node *)malloc(sizeof (Node));
if(pnew == NULL)
{
fprintf(stderr, "Unable to allocate memory! \n");
exit(1);
}
CopyToNode (item,pnew);
pnew ->next =NULL;
if(QueueIsEmpty(pq))
pq ->front = pnew;
else
pq ->rear->next = pnew;
pq -> rear = pnew;
pq -> items++;
return true;
}
bool DeQueue(Item * pitem, Queue *pq)
{
Node *pt;
if(QueueIsEmpty(pq))
return false;
CopyToItem(pq -> front,pitem);
pt = pq ->front;
pq -> front = pq ->front->next;
free(pt);
pq ->items --;
if(pq -> items ==0)
pq ->rear = NULL;
return true;
}
void EmptyTheQueue (Queue *pq)
{
Item dummy;
while (!QueueIsEmpty(pq))
DeQueue(&dummy,pq);
}
static void CopyToNode(Item item,Node *pn)
{
pn ->item = item;
}
static void CopyToItem(Node *pn, Item *pi)
{
*pi = pn ->item;
}
USE.c 源代码
#include <stdlib.h>
#include <stdio.h>
#include <mcheck.h>
#include "queue.h"
int main()
{
Queue line;
Item temp;
char ch;
mtrace();
InitializeQueue(&line);
puts("testing the queue .Type a to add a value");
puts("type d to delete a value , and type q to quit");
while((ch = getchar()) != 'q')
{
if(ch != 'a' && ch != 'd')
continue;
if(ch == 'a')
{
printf("Integer to add: ");
scanf("%d",&temp);
if(!QueueIsFull(&line))
{
printf("putting %d into queue \n", temp);
EnQueue(temp, &line);
}
else
puts("Queue is full");
}
else
{
if (QueueIsEmpty(&line))
puts ("Nothing to delete");
else
{
DeQueue(&temp, &line);
printf("Removeing %d from queue \n",temp);
}
}
printf("%d items in queue \n",QueueItemCount(&line));
puts("Type a to add . d to delete, q to quit:");
}
EmptyTheQueue(&line);
puts("Bye!");
return 0;
} |
|