队列的链式存储结构

2/10/2017来源:ASP.NET技巧人气:319

/*
    IDE: Dev-C++ 5.11
    GCC-version: 4.9.2 64-bit
*/
#include <stdio.h>
#include <malloc.h>

typedef int sElemType;

typedef struct node {
	sElemType e;
	node* next;
} NODE;

typedef struct queue {
	int lenght;
	NODE* front;
	NODE* rear;
} queue;

NODE* create_node(sElemType e) {
	NODE* n = (NODE*) malloc(sizeof(NODE));
	n->e = e;
	n->next = NULL;
}

void init_queue(queue* q, sElemType num) {
	q->lenght = 0;
	q->front = create_node(num);
	q->front->next = create_node(num);
	q->rear = q->front->next;
}

void in_queue(queue* q, sElemType e) {
	q->lenght++;
	q->rear->e = e;
	q->rear->next = create_node(0);
	q->rear = q->rear->next;
}

bool out_queue(queue* q, sElemType* e) {
	if (q->front == q->rear) {
		return false;
	}
	q->lenght--;
	*e = q->front->e;
	NODE* p = q->front;
	q->front = q->front->next;
	free(p);

	return true;
}


int main() {

	queue* q = (queue*) malloc(sizeof(queue));
	init_queue(q, 0);
	in_queue(q, 1);
	in_queue(q, 2);
	in_queue(q, 3);

	q->front = q->front->next;
	
	PRintf("%d\n", q->lenght);

    sElemType e;
	while (out_queue(q, &e)) {
	    printf("%d ", e);
	}


	return 0;
}