用队列实现杨辉三角

头文件如下:

#ifndef _QUEUE_H
#define _QUEUE_H

#define Success 10000
#define Failure 10001
#define SIZE 1023

#include <stdio.h>
#include <stdlib.h>

struct queue
{
	int front;
	int rear;
	int data[SIZE];
};

typedef struct queue SQ;

int QueueInit(SQ *q);
int QueueEmpty(SQ q);
int QueueEnter(SQ *q, int e);
int QueueLength(SQ *q);
int QueueQuit(SQ *q);
int GetFront(SQ q);
int QueueClear(SQ *q);

#endif

功能函数如下:

#include "Queue.h"

int QueueInit(SQ *q)
{
	if(q == NULL)
	{
		return Failure;
	}

	q->front = q->rear = 0;
	
	return Success;
}

int QueueEmpty(SQ q)
{
	return (q.front == q.rear) ? Success : Failure;
}

int QueueEnter(SQ *q, int e)
{
	if(q == NULL)
	{
		return Failure;
	}
	
	if((q->rear + 1) % SIZE == q->front)
	{
		return Failure;
	}
	q->data[q->rear] = e;
	q->rear = (q->rear + 1) % SIZE;

	return Success;
}

int QueueQuit(SQ *q)
{
	if(q == NULL)
	{
		return Failure;
	}
	if(q->rear == q->front)
	{
		return Failure;
	}
	int e;
	e = q->data[q->front];
	q->front = (q->front + 1) % SIZE;

	return e;
}

int QueueLength(SQ *q)
{
	if(q == NULL)
	{
		return Failure;
	}

	return (q->rear - q->front + SIZE) % SIZE;
}

int GetFront(SQ q)
{
	if(q.rear == q.front)
	{
		return Failure;
	}
	return q.data[q.front];
}

int QueueClear(SQ *q)
{
	if(q == NULL)
	{
		return Failure;
	}
	q->rear = q->front;
	return Success;
}

主函数如下:

#include "Queue.h"

int main()
{
	SQ s1, s2;
	int num = 0, i = 0;

	if(QueueInit(&s1) == Failure || QueueInit(&s2) == Failure)
	{
		printf("Init Failure!\n");
		return -1;
	}

	QueueEnter(&s1, 0);
	QueueEnter(&s1, 1);
	QueueEnter(&s1, 0);

	printf("Please input a number:\n");
	scanf("%d", &num);

	for(i = 0; i < num; i++)
	{
		s2 = s1;
		QueueQuit(&s1);
		while(GetFront(s1) != 0)
		{
			printf("%d	", QueueQuit(&s1));
		}
		QueueQuit(&s1);
		putchar('\n');

		QueueEnter(&s1, 0);
		do
		{
			QueueEnter(&s1, QueueQuit(&s2) + GetFront(s2));
		}while(GetFront(s2) != 0);
		QueueEnter(&s1, 0);
	}

	return 0;
}

 

 

 

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/qq_42200028/article/details/81514917
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞