By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,955 Members | 1,768 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,955 IT Pros & Developers. It's quick & easy.

code not workin as wanted ?need help!!!

P: 2
#include<stdlib.h>
#include<alloc.h>
#include<stdio.h>
#include<conio.h>

struct node
{
int data;
node *link;
};

void append(struct node *q,int num)
{
struct node *temp;
temp=q;
if(q==NULL)
{
q=new node;
temp=q;
}
else
{
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=new node;
temp=temp->link;
}
temp->data=num;
temp->link=NULL;
}

void display(struct node *q)
{
printf("\n");
while(q!=NULL)
{
printf("%d",q->data);
q=q->link;
}
}

count(struct node *q)
{
int c=0;
while(q!=NULL)
{
q=q->link;
c++;
}

return c;
}

main()
{
struct node *p;
p=NULL;
printf("\nNo. of elements in the linked list = %d",count(p));

append(p,1);
append(p,2);
append(p,3);

printf("\nNo. of elements in the linked list = %d",count(p));
//clrscr();
display(p);
return 0;
}
Aug 11 '07 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
struct node *p;
p=NULL;
printf("\nNo. of elements in the linked list = %d",count(p));

append(p,1);
append(p,2);
append(p,3);
All you are doing here is sending a null pointer to your append function three times. Your append function creates a new node, fails to put the data in the node, and returns without appending anything.

The only time it will append is if you pass a non-zero node*. And if you do this, it will create a new node and try rto append it.

In main() your p is not changing the way you had in mind because the append function has made a copy of it and is making changes to the copy. When append completes, the copy of p is destroyed leaving p in main() at zero.

One solution is to pass the address of p to append. That way append can rereference the address of p to make changes to p itself.

Expand|Select|Wrap|Line Numbers
  1. append(&p,1);
  2.  
  3. //where:
  4.  
  5. void append(struct node **q,int num)
  6. {
  7.      *q = new node;   //changes the p in main().
  8. }
  9.  
Start with this in mind and let me know how you are comin along.
Aug 11 '07 #2

P: 2
ur suggestion is workin fine
thanx for helping me out.
Aug 12 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.