Question: Suppose that you have a list of numbers: 1 2 3 4 5-1 1 2 3 4 5 67 8 9 10 -2 11 12 -3 1 2 3 4 5 . You have to read the numbers without printing them until a negative number is read. When you find a negative number, then stop reading and print five items from the list. If there are fewer than five items, then print an error message and stop the program. Use Queue to solve the problem
and write down an appropriate algorithm and output for this problem.
Solution:
#include
#include
struct node{
int data;
struct node *next;
}*top = NULL;
typedef struct node* snode;
void push(int data){
snode newNode = (snode)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = top;
top = newNode;
}
int pop(){
int data = top->data;
top = top->next;
return data;
}
int main(){
int data,n;
printf("-------------------------------------------------------------------\n");
printf(" Linked list implementation of Stack to solve \n");
printf("-------------------------------------------------------------------\n");
printf("Type 0 for stop this program\n");
printf("Enter unlimited integers value: \n");
printf("Enter List of Number: \n");
while(scanf("%d",&data)){
if(data>0)
push(data);
else{
if(top == NULL){
printf("\nError!!");
return 0;
}
printf("Output: \n");
int c =0;
while(top != NULL){
if(c<5){
printf("%d ",pop());
c++;
}
else{
printf("Error!!!");
exit(1);
}
}
if(c>5) exit(1);
printf("\n");
printf("Enter List of Number: \n");
}
}
}