Skip to content

Instantly share code, notes, and snippets.

@luizperes
Created October 5, 2016 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizperes/297a8b870a52ddb178c36e3983bce233 to your computer and use it in GitHub Desktop.
Save luizperes/297a8b870a52ddb178c36e3983bce233 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
struct _Node {
int data;
struct _Node *next;
};
typedef struct _Node Node;
void enqueue(Node **headElement, Node **tailElement, int data);
int dequeue(Node **headElement, Node **tailElement);
void show_queue(Node *headElement);
int main()
{
Node *head = NULL;
Node *tail = NULL;
enqueue(&head, &tail, 2);
enqueue(&head, &tail, 5);
enqueue(&head, &tail, 1);
dequeue(&head, &tail);
show_queue(head);
return 0;
}
void enqueue(Node **headElement, Node **tailElement, int data)
{
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL; // if you do not do it you might get garbage
if (!*tailElement) {
*tailElement = node;
*headElement = node;
} else {
(*tailElement)->next = node;
*tailElement = node;
}
}
int dequeue(Node **headElement, Node **tailElement)
{
Node *node = *headElement;
int data = node->data;
*headElement = (*headElement)->next;
free(node);
if (!(*headElement)) {
*tailElement = NULL;
}
return data;
}
void show_queue(Node *headElement)
{
Node *tempNode = headElement;
int i = 1;
while(tempNode) {
printf("Node: %i Data Value: %i\n", i++, tempNode->data);
tempNode = tempNode->next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment