C语言实现-链队列

链队列-涵测试代码

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

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

typedef struct Queue {
	Node head, *tail; //定义一个虚拟头结点和尾指针 
	int length; 
} Queue; 

Node *getNewNode(int);//创建新节点
Queue *init_queue();//初始化一个队列
void clear_node(Node *);//释放一个结点
void clear_queue(Queue *);//释放一个队列
int push(Queue *,int);//进队
int pop(Queue *);//出队
int empty(Queue *);//判断队列是否为空
int front(Queue *);//获取队头元素的值
void output(Queue *);//输出函数

Node *getNewNode(int value) {
	Node *p = (Node *)malloc(sizeof(Node));
	p->data = value;//指针只能 指向-> 
	p->next = NULL;
	return p;
} 

Queue *init_queue() {
	Queue *q = (Queue *)malloc(sizeof(Queue));
	q->head.next = NULL;
	q->tail = &(q->head);
	q->length = 0;
	return q;
}

int empty(Queue *q) {	
	return q->length == 0;
}

int push(Queue *q, int value) {
	if(q == NULL) return 0;
	Node *temp = getNewNode(value);
	q->tail->next = temp;
	q->tail = temp;
	q->length += 1;
	return 1;
	
}

int pop(Queue *q) {
	if(q == NULL) return 0;
	if(empty(q)) return 0;
	Node *temp = q->head.next;
	q->head.next = temp->next;
	clear_node(temp);
	q->length -= 1;
	if(q->length == 0) q->tail = &(q->head);//队尾指向虚拟头结点
	return 1;
}

int front(Queue *q) {
	return q->head.next->data;
}

void output(Queue *q) {
	if(q == NULL) {
		printf("Sorry! This is a empty queue.");
		return;
	}
	printf("Queue(%d) : [", q->length);
	for(Node *p = q->head.next; p != NULL; p = p->next) {
		p != q->head.next && printf(", ");
		printf("%d", p->data);
	}
	printf("]\n");
	return ;
}
void clear_node(Node *node) {
	if(node == NULL) return ;
	free(node);
	return ;
}

void clear_queue(Queue *q) {
	if(q == NULL) return ;
	Node *p = q->head.next, *temp;
	while(p != NULL) {
		temp = p->next;
		clear_node(p);
		p = temp;
	}
	free(q);
	return ;
}
int main() {//主函数主要写测试方法
	srand(time(0));//生成随机种子
	Queue *q = init_queue();
	#define MAX_OP 20
	for(int i = 0; i < MAX_OP; i++) {
		printf("%d st \n", i);
		int op = rand() % 4;
		int value = rand() % 100;
		switch(op) {
			case 0: 
			case 1:
			case 2: {
				printf("push %d to queue = %d \n", value, push(q, value));
				
			}break;
			case 3: {
				printf("pop %d from the queue = ", front(q));
				printf("%d\n", pop(q));
				
			}break;
		}
		output(q), printf("\n");
		
	}
	#undef MAX_OP
	clear_queue(q);
	return 0;
}

如有疑惑,可在下方评论留言

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值