연결리스트 큐(Queue)
#include <stdio.h>
#include <stdlib.h>
#define ERROR_CODE 65000
typedef int element;
typedef struct node{
element data;
struct node* link;
}Node;
typedef struct{
Node* front;
Node* rear;
}LinkedQueue;
LinkedQueue* createQueue(){
LinkedQueue *q=(LinkedQueue*)malloc(sizeof(LinkedQueue));
q->front=NULL;
q->rear=NULL;
return q;
}
int isEmpty(LinkedQueue* q){
if(q->front==NULL)return 1;
else return 0;
}
int enQueue(LinkedQueue* q, element data){
Node* newNode = (Node*)malloc(sizeof(Node));
if(newNode == NULL){ //예외처리(노드를 위한 메모리 할당 실패)
printf("Memory allocation error!\n");
return 0;
}
newNode->data = data;
newNode->link = NULL;
if(isEmpty(q)){ //처음 삽입 할 때
q->front = newNode;
q->rear = newNode;
}
else{
q->rear->link = newNode;
q->rear = newNode;
}
return 1;
}
element deQueue(LinkedQueue* q){
Node*temp;
element data;
if(isEmpty(q)){
printf("Queue is Empty\n");
return ERROR_CODE;
}
temp = q->front;
data = temp->data;
if(q->front == q->rear){ //노드가 하나 남은 경우
q->front = q->rear = NULL;
}
else{
q->front= q->front->link;
}
free(temp);
return data;
}
element peek(LinkedQueue *q){
if(isEmpty(q)){
printf("Queue is Empty\n");
return ERROR_CODE;
}
return q->front->data;
}
void printQueue(LinkedQueue *q){
Node* temp = q->front;
while(temp != NULL){
printf("%d\t", temp->data);
temp = temp->link;
}
printf("\n");
}
int main(){
LinkedQueue *q1, *q2 ;
q1 = createQueue();
q2 = createQueue();
enQueue(q1,10);
printQueue(q1);
enQueue(q1,20);
printQueue(q1);
enQueue(q1,30);
printQueue(q1);
deQueue(q1);
printQueue(q1);
deQueue(q1);
printQueue(q1);
deQueue(q1);
printQueue(q1);
return 0;
}