linkedqueue.h
#ifndef __LINKED_QUEUE_H__
#define __LINKED_QUEUE_H__
#include <stdlib.h>
#include <stdio.h>
typedef int datatype;
typedef struct Node{
union{
int len;
datatype data;
};
struct Node *next;
}*linkedlist;
typedef struct Queue{
linkedlist front;
linkedlist rear;
}*linkedqueue;
linkedqueue create();
linkedlist create_node();
int enqueue(linkedqueue,datatype);
int dequeue(linkedqueue);
void output(linkedqueue);
linkedqueue free_space(linkedqueue);
#endif
linkedqueue.c
#include "linkedqueue.h"
linkedqueue create(){
linkedqueue myQueue = (linkedqueue)malloc(sizeof(struct Queue));
if(myQueue == NULL){
return NULL;
}
linkedlist head = (linkedlist)malloc(sizeof(struct Node));
if(head == NULL){
return NULL;
}
head->len = 0;
head->next = NULL;
myQueue->front = head;
myQueue->rear = head;
return myQueue;
}
linkedlist create_node(){
linkedlist node = (linkedlist)malloc(sizeof(struct Node));
if(node == NULL){
return NULL;
}
node->data = 0;
node->next = NULL;
return node;
}
int enqueue(linkedqueue myQueue,datatype e){
if(myQueue == NULL){
return -1;
}
linkedlist newNode = create_node();
if(newNode == NULL){
return -1;
}
linkedlist p = myQueue->rear;
newNode->next = p->next;
newNode->data = e;
p->next = newNode;
myQueue->rear = newNode;
myQueue->front->len++;
printf("Element %d is enqueued.\n",myQueue->rear->data);
//printf("The length is %d\n",myQueue->front->len);
return 0;
}
int dequeue(linkedqueue myQueue){
if(myQueue == NULL || myQueue->front == myQueue->rear){
return -1;
}
linkedlist p = myQueue->front->next;
if(p == myQueue->rear){
myQueue->rear = myQueue->front;
}
int temp = p->data;
myQueue->front->next = p->next;
free(p);
p = NULL;
myQueue->front->len--;
//printf("The length is %d\n",myQueue->front->len);
return temp;
}
void output(linkedqueue myQueue){
if(myQueue == NULL || myQueue->front == myQueue->rear){
printf("The queue is empty or doesn't exist.\n");
return;
}
linkedlist p = myQueue->front;
while(p->next){
p = p->next;
//printf("Element %d in the queue\n",p->data);
}
}
linkedqueue free_space(linkedqueue myQueue){
if(myQueue == NULL){
return NULL;
}
while(myQueue->rear != myQueue->front){
dequeue(myQueue);
}
free(myQueue->front);
myQueue->front = NULL;
myQueue->rear = NULL;
free(myQueue);
myQueue = NULL;
return myQueue;
}
linkedqueue_main.c
#include "linkedqueue.h"
int main(int argc, const char *argv[])
{
linkedqueue myQueue = create();
for(int i = 0; i < 5;i++){
enqueue(myQueue,i);
}
output(myQueue);
for(int i = 0;i < 2;i++){
int temp = dequeue(myQueue);
printf("%d is dequeued.\n",temp);
}
output(myQueue);
myQueue = free_space(myQueue);
return 0;
}