I'm learning C++ and also about data structures, so I am trying to implement some. This is my linked list. I've included two different ways of getting the length of the list, with a length
variable and also a function (getLength2
) that goes through the list until it finds a NULL
pointer. I suspect that there could be memory leaks in it, though I'm not sure.
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class val>
class linked_list{
struct node{
val value;
node *next;
};
node *start;
unsigned int length;
public:
linked_list() { length = 0; start = NULL; }
unsigned int getLength() { return length; }
val getFirst() { return (*start).value; }
unsigned int getLength2();
void add(val value);
val getVal(unsigned int pos);
val pop();
};
int _tmain(int argc, _TCHAR* argv[])
{
linked_list<int> gary;
for (int i = 0; i < 10; ++i){
gary.add(pow(2, i));
}
for (int k = 0; gary.getLength() > 0; ++k){
cout << gary.pop() << ' ' << gary.getLength() << endl;
}
return 0;
}
template <class val>
void linked_list<val>::add(val value){
node *second = start;
start = new node;
(*start).value = value;
(*start).next = second;
length += 1;
}
template <class val>
val linked_list<val>::getVal(unsigned int pos){
node current = *start;
for (unsigned int depth = 0; depth < pos; ++depth){
current = *(current.next);
}
return current.value;
}
template <class val>
val linked_list<val>::pop(){
val ret = start->value;
node *new_address = start->next;
delete start;
start = new_address;
length -= 1;
return ret;
}
template <class val>
unsigned int linked_list<val>::getLength2() {
if (start == NULL){
return 0;
}
node current = *start;
unsigned int len = 1;
while (current.next != NULL){
current = *(current.next);
len += 1;
}
// should this have a 'delete current'?
return len;
}