C언어 링크드 큐 구현

1 개념[편집]

Linked Queue, 링크드 큐
  • C언어 링크드 큐 구현

2 예시[편집]

  • 0~3까지 값을 큐에 넣었다가 하나씩 빼며 출력
#include <stdio.h>
#include <stdlib.h>

// node typedef
typedef struct nodeTag { 
    int a; 
	struct nodeTag *next; 
} nodeType;

// queue typedef
typedef struct queteTag {
	nodeType *front;
	nodeType *rear;
	int count;
} queueType;

// createQueue
void createQueue(queueType **queue)
{
	*queue = (queueType *)malloc(sizeof(queueType));
	(*queue)->front = NULL;
	(*queue)->rear = NULL;
	(*queue)->count = 0;
}

// createNode
nodeType *createNode(int a)
{
	nodeType *node;

	node = (nodeType *)malloc(sizeof(nodeType));
	node->a = a;
	node->next = NULL;

	return node;
}

// enQueue
void enQueue(queueType *queue, nodeType *node)
{
	if (queue->front == NULL) {
		queue->front = node;
		queue->rear = node;
	}
	else {
		queue->rear->next = node;
		queue->rear = node;
	}
	queue->count++;
}

// deQueue
nodeType *deQueue(queueType *queue)
{
	nodeType *node;

	node = queue->front;
	
	if (queue->front->next == NULL) {
		queue->front = NULL;
		queue->rear = NULL;
	}
	else {
		queue->front = queue->front->next;
	}
	queue->count--;

	return node;
}

// destroyNode
void destroyNode(nodeType *node)
{
	free(node);
}

// isEmpty
int isEmpty(queueType *queue)
{
	if (queue->count == 0)
		return 1;
	else
		return 0;
}

// destroyQueue
void destroyQueue(queueType *queue)
{
	nodeType *node;

	while (!isEmpty(queue)) {
		node = deQueue(queue);
		destroyNode(node);
	};
	free(queue);
}

int main()
{
	queueType *queue;
	nodeType *node;

	createQueue(&queue);

	enQueue(queue, createNode(0));
	enQueue(queue, createNode(1));
	enQueue(queue, createNode(2));
    enQueue(queue, createNode(3));
	
	while(!isEmpty(queue)) {
		node = deQueue(queue);
		printf("%d\n", node->a);
		destroyNode(node);
	}
	destroyQueue(queue);
}

3 같이 보기[편집]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}