6.数据结构之链表实现队列

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

typedef struct Node
{
	int val;
	struct Node* next;
}Node;

typedef struct Queue
{
	Node* head;
	Node* tail;
}Queue;


Node* initNode(int val)
{
	Node* n = (Node*)malloc(sizeof(Node));
	n->val = val;
	n->next = NULL;
	return n;
}


void freeNode(Node* n)
{
	if (n) free(n);
	return;
}


Queue* initQueue()
{
	Queue* q = (Queue*)malloc(sizeof(Queue));
	q->head = NULL;
	q->tail = NULL;
	return q;
}


void freeQueue(Queue* q)
{
	if (!q) return;
	Node* p = q->head, * k;
	while (p)
	{
		k = p;
		p = p->next;
		freeNode(k);
	}
	free(q);
	return;
}

bool push(Queue* q, int val)
{
	if (!q) return 0;
	Node* n = initNode(val);

	if (q->tail)
	{
		q->tail->next = n;
		q->tail = n;
	}
	else 
	{
		q->head = n;
		q->tail = n;
	}
	return true;
}

bool isEmpty(Queue* q)
{
	return !(q && q->head);
}

int pop(Queue* q)
{
	Node* k = q->head;
	int t = k->val;
	q->head = k->next;
	freeNode(k);

	if (!q->head) {
		q->tail = NULL;
	}

	return t;
}


void showQueue(Queue* q)
{
	if (!q) return;
	printf("Stack:[");
	Node* p = q->head;
	while (p)
	{
		printf("%d->", p->val);
		p = p->next;
	}

	printf("NULL]\n");
	return;
}


int main()
{
	srand(time(0));
	Queue* q = initQueue();
	int cnt = 20;
	while (cnt--)
	{
		int val = rand() % 100;
		int op = rand() % 4;
		switch (op)
		{
		case 0:
		case 1:
		case 2:
			printf("push %d,res=%s\n", val, push(q, val) ? "SUS" : "ERR");
			break;
		case 3:
			isEmpty(q) ? printf("pop nothing!\n") : printf("pop %d \n", pop(q));
		}
		showQueue(q);
	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值