队列和其代码的两种实现

/*************************************************************************
	> File Name: quene1.c
	> Author: RoseSec
	> Mail: rosesecno1@hotmail.com 
	> Created Time: Wed 01 Jun 2016 08:47:37 AM EDT
 ************************************************************************/

#include <stdio.h>
#include <stdbool.h>

typedef int DataType;
typedef struct
{
	DataType data[6];
	int front; int rear;
} Quene2;

void init(Quene2 *q)
{
	q->front = q->rear = 0;
}

bool empty(Quene2 *q)
{
	return q->rear - q->front == 0;
}

bool push(Quene2 *q, DataType d)
{
	if(q->rear - q->front == 6)
		return false;
	q->data[q->rear++ % 6] = d;
	return true;
}

bool pop(Quene2 *q)
{
	if(empty(q))
		return false;
	q->front++;
	return true;	}

DataType getFront(Quene2 *q)
{
	return q->data[q->front % 6];
}

int main()
{
	Quene2 q2;
	init(&q2);
	
	for(int i = 0; i < 6; i++)
		push(&q2, i);
	pop(&q2);
	push(&q2, 300);
	pop(&q2);
	pop(&q2);
	push(&q2, 100);
	while(!empty(&q2))
	{
		printf("%d  ", getFront(&q2));
		pop(&q2);
	}

	printf("\n");

	return 0;
}

/*************************************************************************
	> File Name: quene2.c
	> Author: RoseSec
	> Mail: rosesecno1@hotmail.com 
	> Created Time: Wed 01 Jun 2016 09:12:46 AM EDT
 ************************************************************************/

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

typedef int DataType;

typedef struct node
{
	int data;
	struct node *next;
} Node;

typedef struct
{
	Node *head;
	Node *rear;
	int size;
} Quene;

void init(Quene *q)
{
	q->head = q->rear = NULL;
	q->size = 0;
}

bool empty(Quene *q)
{
	return q->size == 0;
}

void push(Quene *q, DataType d)
{
	Node *temp = (Node *)malloc(sizeof(Node));
	temp->data = d;
	temp->next = NULL;
	
	if(empty(q))
	{
		q->head = temp;
		q->rear = temp;
		printf("push:%d \n", temp->data);
	}
	else
	{
		printf("push:%d \n", temp->data);
		q->rear->next = temp;
		q->rear = temp;
	}
	
	q->size++;
	printf("size =%d\n", q->size);
}

void pop(Quene *q)
{
	if(empty(q))
		return;
	Node *tmp = q->head;
	q->head = q->head->next;
	printf("pop:%d \n", tmp->data);
	free(tmp);
	q->size--;
	printf("size =%d\n", q->size);
}

DataType topData(Quene *q)
{
	if(empty(q))
		return -1;
	return q->head->data;
}

int main()
{
	Quene *q = (Quene*)malloc(sizeof(Quene));
	init(q);
	
	push(q, 300);
	push(q, 300);
	push(q, 700);

	Node *t = q->head;
/*
	while(t!= NULL)
		printf("%d ", t->data), t = t->next;
	printf("\n");
  */
	while(!empty(q))
	{
	
		printf("%d ", topData(q));
		pop(q);
	}

	puts("");
	return 0;
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值