Stack in C++ Using Linked List

Stack in C++ Using Linked List

Here you will find out about stack in C++ utilizing a program model.

The stack is a dynamic datatype which pursues Last In First Out (LIFO) rule. Fundamentally stack has two tasks to be a specific push and pop.

push: embeddings a component at the highest point of the stack

pop: expelling a component from the highest point of the stack

Underneath code tells you the best way to actualize stack in C++ utilizing connected rundown information structure.

Program for Stack in C++

#include<iostream>
#include<process.h>
 
using namespace std;
 
struct Node
{
	int data;
	Node *next;
}*top=NULL,*p;
 
Node* newnode(int x)
{
	p=new Node;
	p->data=x;
	p->next=NULL;
	return(p);
}
 
void push(Node *q)
{
	if(top==NULL)
		top=q;
	else
	{
		q->next=top;
		top=q;
	}
}
 
void pop(){
	if(top==NULL){
		cout<<"Stack is empty!!";
	}
	else{
		cout<<"Deleted element is "<<top->data;
		p=top;
		top=top->next;
		delete(p);
	}
}
 
void showstack()
{
	Node *q;
	q=top;
 
	if(top==NULL){
		cout<<"Stack is empty!!";
	}
	else{
		while(q!=NULL)
		{
			cout<<q->data<<" ";
			q=q->next;
		}		
	}
}
 
int main()
{
	int ch,x;
	Node *nptr;
	
	while(1)
	{
		cout<<"\n\n1.Push\n2.Pop\n3.Display\n4.Exit";
		cout<<"\nEnter your choice(1-4):";
		cin>>ch;
		
		switch(ch){
			case 1: cout<<"\nEnter data:";
					cin>>x;
					nptr=newnode(x);
					push(nptr);
					break;
			
			case 2: pop();
					break;
					
			case 3: showstack();
					break;
			
			case 4: exit(0);
			
			default: cout<<"\nWrong choice!!";
		}
	}
	
	return 0;
}

Output

1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4):1

Enter data:7
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4):1

Enter data:8
1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4):3
8 7

1.Push
2.Pop
3.Display
4.Exit
Enter your choice(1-4):4

Recent Posts

error: Alert: Content is protected!!