next pointer in linked list
Here is my code for a linked list.
LinkedList.h
Code:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class LinkedList
{
public:
LinkedList();
~LinkedList();
void createNode(char name[]);//creates a node at end of list
void dump();//prints contents of all nodes
private:
unsigned int length;
struct Node
{
char name[20];
Node *next;
};
Node *startPointer;
};
#endif // LINKEDLIST_H
LinkedList.cpp
Code:
#include <cstdlib>
#include <iostream>
#include <string.h>
#include "..\include\LinkedList.h"
LinkedList::LinkedList() : length(0), startPointer(NULL)
{
}
LinkedList::~LinkedList()
{
}
void LinkedList::createNode(char name[])
{
if(startPointer == NULL)
{
startPointer = new Node;//Node is a struct
(*startPointer).next = NULL;
strcpy((*startPointer).name, name);
}
else
{
Node *temp = startPointer;
while((*temp).next != NULL)
temp = (*temp).next;
(*temp).next = new Node;
temp = (*temp).next;
strcpy((*temp).name, name);
(*temp).next = NULL;
}
}
void LinkedList::dump()
{
Node *temp = startPointer;
std::cout << (*temp).name << std::endl;
while((*temp).next != NULL)
{
temp = (*temp).next;
std::cout << (*temp).name << std::endl;
}
}
In a previous thread it was mentioned that I could set the next pointer to null using the constructor of the struct. I found an example from this website
Code:
struct node
{
node(int data_p) { data=data_p; next=0; }
int data;
node *next;
};
In my header file why can't I do this?
Code:
struct Node
{
char name[20];
Node *next = null;
};
What's so special about initializing the variables the first way?
What's the best way of doing this?