Struct, linked list, head,null-pointer, C++ -
how can define,that pointer head shows first linked list element?the compiler shows mistake in place :
head=domino->info;
struct dominopart { int number1; int number2; }; struct dominoone { dominopart info; struct dominoone *next; };
first defined null-pointer,because linked list empty @ first.
struct dominoone* next= null; struct dominoone* head=null;
then information file read line line.
int readdomino (){ file *datei; if((datei=fopen("datei.dat", "r") )==null) { std::cout<<"file can't opened"<<std::endl; return 0; }else { int beginning; int temp; fscanf(datei, "%d", &beginning); for(int i=0; i<beginning; i++) { dominoone *domino= new dominoone; fscanf(datei, "%i", &temp); domino->info.number1=temp; fscanf(datei, "%i", &temp); domino->info.number2=temp; printf("[%d:%d]", domino->info.number1, domino->info.number2); domino->next=0; if(i==1) { head=domino->info; //the compiler shows mistake here } } }return 0; }
the file read , shows this,that have written in file correctly,but can't delete whole list,because pointer head still null-pointer:
void del () { dominoone* tmp; while(head != 0) { tmp=(head)->next; delete head; head=tmp; } }
there few errors in code.
first assignment head=domino->info
cannot performed since types of left , right sides incompatible.
second, on reading list of dominos, need keep track of tail of list.
so need declare
struct dominoone* tail=null;
then after have populated structure replace if (i==1) ...
with
if (i == 0 ) head = domino; else tail->next = domino; tail = domino;
the final version of readdomino()
function might this:
int readdomino (){ file *datei; struct dominoone* tail=null; if((datei=fopen("datei.dat", "r") )==null) { std::cout<<"file can't opened"<<std::endl; return -1; } int list_size; fscanf(datei, "%d", &list_size); for(int i=0; i<list_size; i++) { dominoone *domino= new dominoone; fscanf(datei, "%i", &domino->info.number1); fscanf(datei, "%i", &domino->info.number2); printf("[%d:%d]\n", domino->info.number1, domino->info.number2); domino->next=null; if (i == 0 ) head = domino; else tail->next = domino; tail = domino; } } return 0; }
Comments
Post a Comment