c++ - Linked list not working for input -
c++ - Linked list not working for input -
i'm writing code takes integers input user , creates linked list , prints out list. however, when come in values 1,2,3,4,5, output 5 5 5 5 5
please tell me wrong here.
the code follows:
include"iostream" using namespace std; struct node { int number; node* next; }; int main() { node* head; head = null; int i,n,x; cin>>n; cout<<endl; for(i=0;i<n;i++) { cin>>x; //insert(x); node* temp; temp = new node; temp->number = x; temp->next = null; head = temp; } //print(); node* temp; temp = head; while(temp != null) { for(int j=0; j<n; j++) cout<<temp->number<<" "; temp = temp->next; } }
remember when setting head
pointer, should when list empty (i.e when head == null
). should after create new node know set head
to:
node* temp = new node; temp->number = x; temp->next = null; if (head == null) // if list empty then... head = temp; // temp start of list
there's problem. temp
supposed added end of list each time it's created. if list empty head
end of list, if list has elements need go end , set next
pointer of node temp
. straightforward, takes while loop iterate on list end:
if (head == null) head = temp; else // list not empty { // need go end node* p = head; while (p->next != null) p = p->next; // maintain going through // p points lastly node p->next = temp; }
there's alternative of keeping prev
node points lastly element inserted. makes don't have go through list each time find end:
node* head = null, prev = null; (/* ... */) { // ... if (head == null) head = prev = temp; else { prev->next = temp; prev = temp; } }
the lastly thing way you're printing. shouldn't have nested loop here:
while (temp != null) { for(int j = 0; j < n; j++) cout << temp->number << " "; temp = temp->next; }
taking out create print correctly.
c++
Comments
Post a Comment