Problems that I see:
f
,nn
,p
, andc
are not initialized.Change the lines to:
struct node { char info; node* link; }; node *f = NULL; node* nn = NULL; node* p = NULL; node* c = NULL;
Change the line
if(f=='\0')
to
if (f == NULL)
This is a style change but more readable. Use
'\0'
only for comparing characters. UseNULL
for comparing pointers.The following line does not seem right.
nn=new node[sizeof(struct node)];
It allocates an array of object containing
sizeof(struct node)
items and returns a pointer to that array. You just need one object. Change the line to:nn=new node;
There are two such lines, one in each of the blocks under
if (f=='\0')
.You are not making the links correctly under the
else
block.nn=new node[sizeof(struct node)]; nn->info=inf; p->link=nn; // This is good only for the second item. // When you add the third item, the second item becomes an orphan. // When you add the fourth item, the third item becomes an orphan. c=nn; c->link='\0';
What you need is:
nn=new node; nn->info=inf; nn->link = NULL; c->next = nn; c = nn;
You are modifying the global variables
p
andc
indisplay
. If you try to add any more items after the call todisplay
, you will get unexpected behavior. Using local variables indisplay
will prevent that problem.void display() { Node* n = f; while( n != NULL) { cout << n->info << " "; n = n->link; } cout << endl; }
Suggested cleanup
You don't need the variable nn
in the global scope. It's used only in create
. Remove it from the global scope and put it in create
.
You don't need the global variable p
at all. The only place you thought it would be useful is in the else
block. But, as you can see, it is not needed there.
Use NULL
instead of '\0'
to compare pointers.