Home Forums C Programming Structures and Algorithms in C++ Re: Re: Structures and Algorithms in C++

#3622
GWILouisaxwzkla
Participant

Heres a simple version ( the items are entered into the list from the back )


/****************************************************************
* File Name : c:programstempCG.cpp
* Date : January,8,2010
* Comments : new project
* Compiler/Assembler : Visual C++ 6.0
* Modifications :
*
*
*
*
*
* Program Shell Generated At: 4:13:24 p.m.
=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


#include < iostream >
//#include < string.h >
//#include < conio.h >
//#include < math.h >
//#include < iomanip >
//#include < ctype.h >

using namespace std;

//node for the list
struct node
{
int data;
node * next;
};



//main function ******************************

int main ( )
{

cout << "enter numbers ( 0 to stop ) " << endl << endl;

node * front = NULL; //front of the linked list
node * temp = NULL;
node * back = NULL;

int input;

cout << "enter number: ";
cin >> input;

//######### READ THE LIST FROM THE KEYBOARD

while ( input != 0 )
{
temp = new node; //make a new node in the list
if ( temp == NULL ) //check that node was allocated properly
{
cout << "allocation error , node not stored! " << endl;
continue;
}
temp -> data = input;//copy data
temp -> next = NULL; //new item has no next item
if ( front == NULL ) //if the list is empty add a new node
{
front = temp; //front of list points to temp
back = temp; //back of list pointer points to temp
}
else //add the item to the back of the list
{
back -> next = temp;//next item in the list is the item read
back = temp; //new item is the new last item
}
cout << "enter number: "; //get the next number
cin >> input;
}


cout << "Printed list: " << endl << endl;

temp = front; //start at the front of the list

//############ PRINT THE LIST

while ( temp ) //while not at the end of the list
{
cout << temp -> data << " " ; //output data in list item
temp = temp -> next; //go to next item in the list
}

//######## DELETE THE LIST

while ( front )
{
temp = front; //save the address of the front node
front = front -> next; //make the next item first
delete temp; //deallocate memory for the old front node
}


return 0 ;
}