Below I have a very simple LinkedList implementation. I was wondering if there are any memory leak problems with this and if I used the pointers correctly. I just started practicing with C++ and hoping to improve my use of pointers and memory leak management.
#include <iostream>
struct node{
int data;
node *next;
node::node(){}
node::node(const int & val, node* link)
: data(val), next(link)
{}
};
class LinkedList
{
public:
LinkedList();
void addToEnd(int val);
void printList();
void deleteList(node *head);
void deleteNode(node *toBeDeleted);
node* get(int index);
private:
int size;
node *head, *tail;
};
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
}
node* LinkedList::get(int index){
node* temp = head;
int pointer = 0;
while(pointer != index){
temp = temp->next;
pointer++;
}
return temp;
}
void LinkedList::addToEnd(int val){
node *temp = new node(val, NULL);
// temp->data = val;
// temp->next = NULL;
if(head==NULL){
head = temp;
tail = temp;
temp = NULL;
}
else{
tail->next = temp;
tail = temp;
}
}
void LinkedList::printList(){
node *temp = head;
//temp = head;
while(temp){
cout<<temp->data<<"\t";
temp = temp->next;
}
}
//Supposed to delete the nodes coming after the input node
void LinkedList::deleteList(node *start){
if(start){
deleteList(start->next);
delete start;
}
}
//deletes a single node
void LinkedList::deleteNode(node* toBeDeleted){
node* temp = head;
if(head == toBeDeleted){
head = head->next;
delete temp;
}
while(temp->next != toBeDeleted){
temp = temp->next;
}
if(temp->next){
temp->next = toBeDeleted->next;
delete toBeDeleted;
}
}
int main(){
LinkedList list;
for(int i=0;i<4;i++){
list.addToEnd(i+1);
}
list.deleteList(list.get(2));
//list.deleteNode(list.get(2));
list.printList();
return 0;
}
Currently, the main function doesn't run after deleteList. I am not necessarily asking about how to fix that part, I just wanted to learn tips about better pointer uses and memory leak possibilities.
Edit:
I have commented the use of deleteList and deleteNode and below I have added a destructor showing how I was planning to use deleteList.
LinkedList::~LinkedList(){
deleteList(head);
}