Skip to content

Instantly share code, notes, and snippets.

@natemcmaster
Created October 9, 2013 02:49
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 natemcmaster/6895435 to your computer and use it in GitHub Desktop.
Save natemcmaster/6895435 to your computer and use it in GitHub Desktop.
Tutoring: example of creating a simple data structure with dynamic memory allocation and avoiding memory leaks
#include <iostream>
#include "queue.hpp"
Queue::Queue():head(NULL),tail(NULL){
}
void Queue::add(int insertValue){
Node* nextItem = new Node();
nextItem->value = insertValue;
if(tail != NULL)
tail->next = nextItem;
tail = nextItem;
if(head == NULL)
head = nextItem;
return;
}
int Queue::pop(){
Node* temp = head;
int popValue = temp->value;
head = head->next;
delete temp;
return popValue;
}
Queue::~Queue(){
removeNode(head);
}
void Queue::removeNode(Node* node){
if(node == NULL)
return;
removeNode(node->next);
delete node;
}
#pragma once
class Queue {
struct Node{
Node* next;
int value;
};
private:
Node* head;
Node* tail;
void removeNode(Node*);
public:
Queue();
void add(int);
int pop();
~Queue();
};
#include <iostream>
#include "queue.hpp"
using namespace std;
int main(){
Queue que;
que.add(4);
que.add(89);
que.add(-32);
cout<< que.pop() <<endl; //prints 4
cout<< que.pop() <<endl; //prints 89
cout<< que.pop() <<endl; //prints -32
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment