Cn anybody give me a program about adding nodes at the end of the list in C?
I just need a basis of a program that I will be creating. I also needed its algorithm. Thanks in advance.
Cn anybody give me a program about adding nodes at the end of the list in C?
I just need a basis of a program that I will be creating. I also needed its algorithm. Thanks in advance.
Your question is incomplete. What list? What type? There are many types of lists.
Taking the list to be a singly ended.
1. Locate End Pointer (endPtr)
2. Create a new node (newPtr)
3. Initialize new node
4. Assign the link part of endPtr the address of newPtr
5. Make newPtr as new endPtr
Your question is incomplete. What list? What type? There are many types of lists.
What I mean is about SINGLY LINKED LIST in C programming.
This issue is directly compatible with this issue on page 1 of the C forum.
http://www.daniweb.com/forums/thread313521.html
Maybe that could help.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node *next;
} ;
typedef struct node nd;
main()
{
int i, x;
nd *head=NULL, *ptr;
clrscr();
head=malloc(sizeof(nd));
ptr=head;
printf("Enter numbers: ");
for(i=0; i<5; i++)
{
scanf("%d", &x);
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->num=x;
ptr->next=NULL;
}
ptr=head;
printf("\n\nValues: ");
for(i=0; i<5; i++)
{
if(ptr!=NULL)
{
printf("\n%d", ptr->num);
}
}
getch;
}
Theres a logical error here but i can't find what it is. The problem is the output goes wrong when I print it. Cn anybody debug this program for me? pls
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next is uninitialized before this loop, so its never NULL, so it will run forever, since next contains garbage and will never be NULL.
I've modified that part and changed it to
while(ptr!=NULL)
{
ptr=ptr->next;
}
but still it doesn't print the right output?
Because you are initializing memory only once.Initialize memory whenever you add a new element.So dont initialize for the head in the start.Initialize memory after the while loop and also you can initialize the value at the same time.
What I meant to say is that you don't have ptr->next=NULL before the while loop
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.