欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链队列的实现

程序员文章站 2024-03-18 12:00:04
...
#include <stdio.h>
#include <stdlib.h>

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

typedef struct{
	node head;
	node tail;
	int num; //队列元素个数
}queue;

void queue_init(queue *ps)
{
	ps->head.next = &(ps->tail);
	ps->tail.next = NULL;
	ps->num = 0;
}

void queue_delete(queue *ps)
{
	node *first = NULL, *mid = NULL, *last = NULL;
	while(ps->head.next != &(ps->tail)){
		first = &(ps->head);
		mid = first->next;
		last = mid->next;
		if(mid != &(ps->tail)){
			first->next = last;
			free(mid);
			mid = NULL;
		}
	}
}

int queue_empty(const queue *ps)
{
	return ps->head.next == &(ps->tail);
}

int queue_size(const queue *ps)
{
	return ps->num;
}

int queue_push(queue *ps, int val)
{
	node *new = NULL;
	new = (node *)malloc(sizeof(node));
	if(!new)
		return 0;
	new->data = val;
	new->next = ps->head.next;
	ps->head.next = new;
	return 1;
}

int queue_pop(queue *ps, int *val)
{
	node *tmp = NULL;
	node *first = NULL, *mid = NULL, *last = NULL;
	if(ps->head.next == &(ps->tail))
		return 0;

	for(tmp = &(ps->head); tmp != &(ps->tail); tmp = tmp->next){
		first = tmp;
		mid = first->next;
		last = mid->next;
		if(last == &(ps->tail)){
			*val = mid->data;
			first->next = last;
			free(mid);
			mid = NULL;
			return 1;
		}
	}
}

int queue_front(const queue *ps, int *val)
{
	node *tmp = NULL;
	if(ps->head.next == &(ps->tail))
		return 0;
	tmp = ps->head.next;
	while(tmp->next != &(ps->tail)){
		tmp = tmp->next;
	}
	*val = tmp->data;
	return 1;
}

int main()
{
	int val = 0, ret = 0;
	queue sk = {0};
	queue_init(&sk);
	while(1){
		printf("input a number:");
		scanf("%d", &val);
		if(val < 0)
			break;
		ret = queue_push(&sk, val);
		if(!ret)
			break;
	}
	while(1){
		ret = queue_pop(&sk, &val);
		if(!ret)
			break;
		printf("%d ", val);
	}
	printf("\n");
	queue_delete(&sk);
	return 0;
}



相关标签: 队列 链队列