TheAlgorithms-C/data_structures/queue.c

99 lines
2.0 KiB
C
Raw Normal View History

2017-07-16 07:00:51 +03:00
////////////////////////////////////////////////////////////////////////////////
// INCLUDES
2017-07-16 07:00:51 +03:00
#include <stdio.h>
#include <stdlib.h>
////////////////////////////////////////////////////////////////////////////////
// MACROS: CONSTANTS
2017-07-16 07:00:51 +03:00
////////////////////////////////////////////////////////////////////////////////
// DATA STRUCTURES
/**
* Defining the structure of the node which contains 'data' (type : integer), two pointers 'next' and 'pre' (type : struct node).
*/
struct node
{
2017-07-16 07:00:51 +03:00
int data;
struct node *next;
struct node *pre;
} * head, *tail, *tmp;
2017-07-16 07:00:51 +03:00
////////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
2017-07-16 07:00:51 +03:00
int count;
////////////////////////////////////////////////////////////////////////////////
// FORWARD DECLARATIONS
2017-07-16 07:00:51 +03:00
void create();
void enque(int x);
int deque();
int peek();
int size();
int isEmpty();
////////////////////////////////////////////////////////////////////////////////
// MAIN ENTRY POINT
2017-07-16 07:00:51 +03:00
int main(int argc, char const *argv[])
{
2017-07-16 07:00:51 +03:00
create();
enque(5);
return 0;
2017-07-16 07:00:51 +03:00
}
void create()
{
2017-07-16 07:00:51 +03:00
head = NULL;
tail = NULL;
}
2017-07-18 04:37:58 +03:00
/**
* Puts an item into the Queue.
*/
void enque(int x)
{
if (head == NULL)
{
2020-10-01 17:28:19 +03:00
head = (struct node *)malloc(sizeof(struct node));
2017-07-16 07:00:51 +03:00
head->data = x;
head->pre = NULL;
tail = head;
}
else
{
2020-10-01 17:28:19 +03:00
tmp = (struct node *)malloc(sizeof(struct node));
2017-07-16 07:00:51 +03:00
tmp->data = x;
tmp->next = tail;
tail = tmp;
}
}
2017-07-18 05:13:45 +03:00
/**
* Takes the next item from the Queue.
*/
int deque()
{
2020-04-21 13:38:03 +03:00
int returnData = 0;
if (head == NULL)
{
2017-07-16 07:00:51 +03:00
printf("ERROR: Deque from empty queue.\n");
exit(1);
}
else
{
2017-07-16 07:00:51 +03:00
returnData = head->data;
if (head->pre == NULL)
2017-07-16 07:00:51 +03:00
head = NULL;
else
head = head->pre;
head->next = NULL;
}
return returnData;
2017-07-16 07:00:51 +03:00
}
2017-07-18 05:13:45 +03:00
/**
* Returns the size of the Queue.
*/
2020-10-01 17:28:19 +03:00
int size() { return count; }