妙趣橫生的算法實例1-5

#include <stdio.h>
#include <malloc.h>

typedef struct qNode
{
	char data;
	struct qNode *next;
}qNode, *queuePtr;

typedef struct 
{
	queuePtr front;
	queuePtr rear;
}linkQueue;

void initQueue(linkQueue *q)
{
	q->front = q->rear = (queuePtr)malloc(sizeof(qNode));
	if(!q->front) return;
	q->front->next = NULL;
}

void enqueue(linkQueue *q, char e)
{
	queuePtr p = (queuePtr)malloc(sizeof(qNode));
	if(!p) return;
	if(!q->front) return;
	p->data = e;
	p->next = NULL;
	q->rear->next = p;
	q->rear = p;
}

void dequeue(linkQueue *q, char *e)
{
	queuePtr p;
	if(q->front == q->rear) return;
	p = q->front->next;
	*e = p->data;
	q->front->next = p->next;	
	if(q->rear == p)
	{
		q->rear = q->front;
	}

	free(p);
}

void destroyQueue(linkQueue *q)
{
	while (q->front)
	{
		q->rear = q->front->next;
		free(q->front);
		q->front = q->rear;
	}
}



void main()
{
	char elem;
	linkQueue queue;
	initQueue(&queue);
	printf("請輸入一段話,以@結束。\n");
	scanf("%c", &elem);
	while (elem != '@')
	{
		enqueue(&queue, elem);
		scanf("%c", &elem);
	}

	printf("請把@符號之前的話輸出:\n");
	//這裏的判斷條件不能寫成while(elem),否則會無線循環下去的
	while (queue.front != queue.rear)
	{
		dequeue(&queue, &elem);
		printf("%c", elem);
	}
	
	printf("\n");
	destroyQueue(&queue);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章