Created
October 9, 2013 02:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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