Um, to be quite honest, I don't separate the node from the head. That is, the head is simply the first object and is never used to store data. It's sole purpose is to tell me whether the list is empty, etc. An entry point.
Here's a non-templated version with integers:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.c>
class List { public:
List *next;
int data;
List(){ next = NULL; data = 0; }
int Count() {
int count = 0;
List *p = this;
while( p->next )
{
p = p->next; //...NOTE: advance pointer - THEN do stuff...
++count;
}
return count;
}
List *GetTail() { List *t = this; while( t->next) t = t->next; return t; }
List *Push( int num ) {
List *g = GetTail();
List *New = new List;
g->next = New;
New->data = num;
return New;
}
int *PopList() {
int counted = Count(), k = 0;
if(!counted) return NULL;
int *array = new int[counted];
List *i = this;
while( i->next )
{
i = i->next;
array[ k++ ] = i->data;
}
return array;
}
};
int main()
{
List nums;
char buff[50];
int *array, count, c = 0;
do{
printf("\n\n\n Enter A Number, Then \"Enter\". \n\n");
printf(" \"x\" Quits...\n\n");
fgets(buff, 50, stdin);
clrscr();
if( !strcmp( buff, "x\n") || !strcmp( buff, "X\n") )
break;
nums.Push( atoi( buff ) );
}while(1);
count = nums.Count();
array = nums.PopList();
printf("Total Numbers Entered: %i\n\n", count);
while( c < count )
{
printf(" %i: %i \n\n", c, array[c++]);
getch();
}
return 0;
}