Answer to Question #231571 in C for Arup

Question #231571

Implement PUSH, POP, and TRAVERSE operations on a stack using linked list.


1
Expert's answer
2021-08-31T17:36:00-0400
#include <stdio.h>
#include <stdlib.h>




struct Stack 
{
	int value;
	struct Stack *next;
} *top;




void push(int n){


	struct Stack * newNode = (struct Stack *) malloc(sizeof(struct Stack));
	newNode->value = n;
	newNode->next = top;        
	top = newNode;


}


int pop()
{
	int data = 0;
	struct Stack * topNode;


	if (!top)
	{
		printf("Stack is empty.\n");
		return -1;
	}
	topNode = top;
	data = top->value;
	top = top->next;
	free(topNode);
	return data;
}


void traverse(){
	if(!top){
		printf("List is empty!\n");
		return;
	}else{
		struct Stack * topNode=top;
		printf("\nAll values in stack:\n");
		while(topNode!=NULL){
			printf("%d\n",topNode->value);
			topNode=topNode->next;
		}
		printf("\n\n");
	}


}


int main()
{
	printf("push: 45\n");	
	push(45);
	printf("push: 5\n");
	push(5);
	printf("push: 2\n");
	push(2);
	printf("push: 10\n");
	push(10);
	printf("push: 20\n");
	push(20);




	traverse();


	printf("pop: %d\n",pop());
	printf("pop: %d\n",pop());


	traverse();




	free(top);


	getchar();
	getchar();


	return 0;
}







Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS