In: Computer Science
Create a C program that performs the following (please comment the codes):
a) Create a Stack ADT. Stack should be implemented using the linked list.
b) Enter 10 random integer numbers between 0 to 50 in the stack.
c) After pushing each element, print the content of the top of the stack.
c) Then pop out those 10 integer numbers and print those numbers.
d) Finally destroy the Stack.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node {
int info;
struct node* link;
} * top;
struct node *top = NULL;
struct node* push(struct node*, int);
struct node* pop(struct node*);
int Elements(struct node*);
int main()
{
srand(time(NULL));
for(int i = 0 ; i<10; ++i){
top = push(top, rand()%50);
printf("Top is: %d \n",top->info);
}
for(int i = 0 ; i<10; ++i)
top = pop(top);
struct node *temp = top;
while(temp != NULL){
struct node *curr = temp;
temp = temp->link;
free(curr);
}
return 0;
}
// Push
struct node* push(struct node* top, int item)
{
struct node* temp;
temp = (struct node *) malloc(sizeof(struct node));
temp->info = item;
temp->link = top;
top = temp;
return top;
}
// Pop
struct node* pop(struct node* top)
{
struct node* temp;
if (top == NULL)
printf("The stack is Empty\n");
else {
temp = top;
printf("Element has been Popped %d \n",temp->info);
top = top->link;
free(temp);
}
return top;
}
// Elements
int Elements(struct node* top)
{
struct node* pointer;
pointer = top;
int count = 0;
if (top == NULL)
return 0;
else {
while (pointer != NULL) {
printf("%d \n", pointer->info);
pointer = pointer->link;
++count;
}
}
return count;
}
=========================================
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern.