Hi, I'm a beginner in C++ and just learned linked lists.I'm trying to write a code which creates a linked list according to the int numbers taken from the user and prints them all.i'm writing the code in Dev c++.However i have a problem in printing the list.By the way my do-while statement seems to have some problems as well.i searched the web but i couldn't make it working.I guess my problem is in the for loop.it never reaches the "else" in for loop.something might be wrong about NULL:/.Anyone help please.Here is my code.Thanks in advance:)

#include <iostream>
using namespace std;

struct Node{
       Node *next;
       int item;       
};

Node *head=new Node;
int size=1;
char answer;
Node *cur=head;
//creating a linked list
Node* createList(){
     int item;

     do{
             cout<<"Enter the item you want to add(-1 to quit) :";
             cin>>item;                                         
             cur->item=item;                  
             cout<<"item "<<cur->item<<" is added to the list"<<endl;
             cur->next=new Node;
             cur=cur->next;                        
             size++;                                                
       }while(item!=-1);
                  cout<<size;
                  cur=NULL;                    
                  Node *ptr=head;
                  Node* ptrNxt=ptr->next;
                  cout<<"List: {";   
                  //printing the entire list
                  for(int i=0;i<(size-1);i++){
                          if(ptrNxt!=NULL){
                             cout<<ptr->item<<",";
                             ptr=ptr->next;
                             ptrNxt=ptrNxt->next;                
                          }
                          else //PROGRAM NEVER REACHES HERE
                               cout<<ptr->item<<"}"<<endl;                 
                  }                        
     return head;    

} 

int main()
{  
   createList();

   system("PAUSE");

}

First of all, next time please use a code tag.
Second, in such situations it is highly recommended to use a debugger.
Third, let's see what happens if the very first answer is -1: size becomes 2, head->item becomes -1, head->next is not NULL.

How many iterations will the printing loop go through? Of course it will never see the final node.

My recommendations:
1. You do not need the if/else inside the loop (hint: you print "{" outside of the loop; why would you want to print "}" from inside?)
2. Do not use size for list traversals. The list has an inherent end marker.

sorry about the code tag its the first time i write on this forum.

From your comments i undrestood that i have some algorithm problems..I will try to fix it.

Thanks for advises

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.