I have this code to sort a linked list which asks the user to add nodes to the lists till the user presses y or Y. But what is happening currently is that after insertion of one node the program moves ahead without waiting for the input from the user. Is it that i am doing something wrong when asking input from the user.
[insert]
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* link;
} *start;
void addatend(struct node**, int);
void display(struct node*);
int count(struct node*);
void selection_sort(int);
void bubble_sort(int);
void getdata();
int main(void)
{
int n;
getdata();
display(start);
n = count(start);
selection_sort(n);
display(start);
n = count(start);
getdata();
display(start);
n = count(start);
bubble_sort(n);
display(start);
n = count(start);
return 0;
}
void getdata()
{
struct node *newnode;
int val;
char ch;
newnode = NULL;
do
{
printf("\nEnter the value");
scanf("%d", &val);
addatend(&newnode, val);
printf("\nAny more nodes");
ch = getchar();
}while (ch == 'y' || ch == 'Y');
start = newnode;
}
void addatend(struct node **q, int data)
{
struct node *temp;
temp = *q;
if(*q == NULL)
{
// adding the first node
*q = malloc(sizeof(struct node));
temp = *q;
}
else
{
// go to last node
while(temp ->link != NULL)
temp = temp->link;
temp->link = malloc(sizeof(struct node));
temp = temp->link;
}
temp ->data = data;
temp ->link = NULL;
}
void display (struct node *q){
int i = 0;
struct node *temp;
temp = q;
while (temp != NULL){
printf("\nThe data at loc %d is %d", i , temp ->data);
temp = temp->link;
i++;
}
}
int count (struct node *q){
struct node *temp;
int count = 0;
temp = q;
while (temp != NULL){
++count;
temp = temp -> link;
}
printf("\nCount %d", count);
return count;
}
void selection_sort(int n)
{
int i,j,temp;
struct node *p, *q;
p = start;
for(i = 0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p->data > q->data)
{
temp = p->data;
p->data = q->data;
q->data = temp;
}
q = q->link;
}
p= p->link;
}
}
void bubble_sort(int n)
{
int i,j,k, temp;
struct node *p,*q;
for(i = 0;i<n-1;i++)
{
p = start;
q = p->link;
for(j=1;j<n;j++)
{
if(p->data > q->data)
{
temp = p->data;
p->data = q->data;
q->data = temp;
}
p= p->link;
q= q->link;
}
}
}