Hi everybody,
i was performing some linked list operations,
the code below adds node to the end of the list by using function
add_node().
first i created a node in main() and then the program asks the user
if he needs any more. now i am going to add other link list operations like delete etc.
Kindly guide if lacking any good programming style or the code below can hav improvements.
Thanks
Code:
#include<stdio.h>
#include<conio.h>
struct node{
int key;
struct node* next;
};
void add_node(struct node* start) {
struct node* temp;
char ch;
temp=start;
while(temp->next!=NULL)
temp=temp->next;
struct node* nd;
nd=(struct node*)malloc(sizeof(struct node));
printf("Enter node value\n");
scanf("%d",&nd->key);
temp->next=nd;
nd->next=NULL;
printf("Do you want to add another node(y/n)\n");
ch=getch();
if(ch=='y')
add_node(start);
else
return;
}
int main()
{
struct node* start,*p,*q;
start=(struct node*)malloc(sizeof(struct node));
printf("Enter first node value\n");
scanf("%d",&start->key);
start->next=NULL;
add_node(start);
for(p=start;p!=NULL;p=p->next)
printf("%d\n",p->key);
for(p=start;p!=NULL;p=q) {
q=p->next;
free(p);
}
getch();
return 0;
}