C++ Sorted Structure Linked List -


i working on project import data text file linked list in order, output linked list. however, whenever output linked list, last entry in text file repeating on , over.

here structure:

struct account {     int accountnumber;     double balance;     string firstname;     string lastname;      account * next; }; 

this function add node in list:

void insertaccountbyaccountnumber(account * & h, account * n) {     if (h == null)     {         h = n;         return;     }     if (h->accountnumber >= n->accountnumber)     {         n->next = h;         h = n;         return;     }     account * t1, *t2;     t1 = h;     t2 = h->next;     while (t2 != null)     {         if (t2->accountnumber < n->accountnumber)         {             t1 = t2;             t2 = t2->next;          }         else         {             n->next = t2;             t1->next = n;             return;         }         t1->next = n;     } } 

and here code create node text file:

account * head = null;  account * currentaccount = new account;  ifstream fin; fin.open("record.txt"); while (fin >> accountnumbercheck) {     fin >> firstnamecheck;     fin >> lastnamecheck;     fin >> balancecheck;     currentaccount->accountnumber = accountnumbercheck;     currentaccount->firstname = firstnamecheck;     currentaccount->lastname = lastnamecheck;     currentaccount->balance = balancecheck;     currentaccount->next = null;     insertaccountbyaccountnumber(* & head, currentaccount); }  showaccounts(head);   fin.close(); 

as nathan mentioned need allocate additional memory each data entry create , add linked list. if need further improvement here one: don`t need additional '&' sign when passing pointer function since address head data. try:

account * head = null;  ifstream fin; fin.open("record.txt"); while (fin >> accountnumbercheck) {     fin >> firstnamecheck;     fin >> lastnamecheck;     fin >> balancecheck;      account * currentaccount = new account; // allocate new memory location each data entry in heap     currentaccount->accountnumber = accountnumbercheck;     currentaccount->firstname = firstnamecheck;     currentaccount->lastname = lastnamecheck;     currentaccount->balance = balancecheck;     currentaccount->next = null;     insertaccountbyaccountnumber(head, currentaccount); }  showaccounts(head);   fin.close(); 

and of course function header be:

void insertaccountbyaccountnumber(account* h, account* n);


Comments

Popular posts from this blog

How to run C# code using mono without Xamarin in Android? -

python - Specify path of savefig with pylab or matplotlib -

c# - SharpSsh Command Execution -