I am trying to create my own datatype that is like a vector or an array.
I am having troubles with my print function; When I go to print the list, it only prints the last item in the list.
// LinkedListClass.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
class Node
{
public:
int value;
Node* next;
Node::Node(int val)
{
value = val;
};
};
class List
{
public:
Node* firstNode;
Node* currentNode;
int size;
List::List()
{
firstNode = NULL;
currentNode = firstNode;
size = 0;
};
void push(Node* node)
{
if(firstNode == NULL)
{
firstNode = node;
firstNode->next = currentNode;
size++;
}
else
{
currentNode = node;
currentNode = currentNode->next;
size++;
}
};
void print()
{
if(firstNode != NULL)
{
Node* printNode = firstNode;
while(printNode->next != NULL)
{
std::cout << "List Item " << printNode->value << std::endl;
printNode = printNode->next;
}
}
};
};
int _tmain(int argc, _TCHAR* argv[])
{
List ll = List();
for(int i = 0; i < 10; ++i)
{
Node val = Node(i);
ll.push(&val);
}
std::cout << ll.firstNode->value << std::endl;
ll.print();
std::cout << "Size " << ll.size << std::endl;
std::cin.ignore();
return 0;
}
/* Output
9
Size 10
*/
I know this is nowhere near completed, but if you have any other pointers (lol), please feel free to suggest.
There are three important errors:
push() — fixed
I think by assigning
firstNode->next = currentNode;you expected the next timecurrentNodewas updated, it would updatefirstNode->nextas well.It doesn’t work that way.
firstNode->next = currentNode;implies that the address stored incurrentNodeis now infirstNode->next. So next time you store something incurrentNode = node;you’re not storing it infirstNode->next. So you have a broken linked list — which is why your output didn’t go very far.Also, this is really bad. By setting
currentNode=nodebefore setting the current node’snextpointer tonode, you’ve broken the list again. You should first pointcurrentNode->nexttonodeand then set thecurrentNodeasnode(nodebeing the node which you’re pushing onto your list).Node val = Node(i);
The scope of
valis only within that iteration of your loop. Once you loop around, it’s off the stack and doesn’t exist anymore. But you’ve copied the pointer of val to your list — so now with the rightpushmethod, you’re just adding a dangling pointer.You need to put it on the heap so it stays on till you don’t need it anymore.
… which leads us to your destructor!
Since you’ve allocated a node, you’ll need to deallocate it. So do that in your destructor — traverse your list and deallocate all those nodes.