question about a working linked list
Hi, this program is the solution to an excercise I found on a book...I wrote it reading tutorials and stuff...my problem is... as you can see in the CreateList function...I have no secondary node pointing to nothing....I have read that you need a second pointer because the first node is unchangeable and the second one is the one that's going to move in the list....but in this code I don't use that second node...so..why does this works correctly? does it have some kind of error? I can't figure it out because I'm kind of new in this kind of programming technique and I have never used linked list before...
can you please tell what am I doing wrong? thanks..
Edit:Sorry that I didn't format my code...I don't know HTML or how to place code...I did read the post about using code tags, but it doesn't specify what code one should use to insert tabs or spaces...
Edit:Ok forget it... I just found out how to do it :P hahaha
Code:
#include <iostream>
using namespace std;
struct linkedList {
int obj_number; //Numbers the current list
linkedList* Next;
};
void CreateList( linkedList* anyList, int nodes ){
for(int i = 0; i < nodes; i++){
anyList->obj_number = i + 1; //put the number of the current node
anyList->Next = new linkedList; //creates a new node at the end of the list
anyList = anyList->Next; //moves to this new node
anyList->Next = 0;
}
}
void DisplayList( linkedList* anyList ){
while( anyList->Next != NULL ){
cout << anyList->obj_number << endl;
anyList = anyList->Next;
}
}
int main(){
linkedList* myList;
myList = new linkedList;
CreateList( myList, 5 );
DisplayList( myList );
cin.get();
delete myList;
}
question about a working linked list
Quote:
Originally Posted by Tonto
Code:
void FreeList(linkedList * list)
{
if(list->Next)
{
FreeList(list->Next);
}
else delete list;
}
Thanks... I didn't know that...but why does the list display correctly if I created the list incorrectly? I mean...it does what it is supposed to do...but the way I did it is not well...
question about a working linked list
Quote:
Originally Posted by Micko
First, please enclose your code using code tags!!!
Second, you have created linked list, how about destroying it? Please try to write functions for adding element to list, removing element from the list, for reversing list and so on...
well..ok I will try to write those functions...but...I have no idea of what I just did...my question is about the program running even though I did it wrong...I don't understand quite well about this linked list thing... :)