stack implementation using linked list in cpp 1

stack implementation using linked list in cpp

#include
using namespace std;
struct node
{
	int data;
	node* next;
};
class Stack
{
private:
	node* top;
public:
	Stack()
	{
		top = NULL;
	}
	void Push(int n)
	{
		node* temp = new node();
		temp->data = n;
		temp->next = NULL;
		if (top == NULL)
		{
			top = temp;
		}
		else
		{
			temp->next = top;
			top = temp;
		}
	}
	void Pop()
	{
		
		if (top == NULL)
		{
			cout << "Error,Stack is Empty!" << endl;
			return;
		}
		node* temp = top;
		top = top->next;
		delete temp;
	}
	void Top()
	{
		cout << "Top Of Stack: " << top->data << endl;
	}
	void Display()
	{
		node* t = top;
		cout << "Stack: ";
		while (t != NULL)
		{
			cout << t->data << " ";
			t = t->next;
		}
		cout << "\n";
	}
	void IsEmpty()
	{
		node* t = top;
		if (t == NULL)
		{
			cout << "Stack Is Empty!" << endl;
		}
		else
		{
			cout << "Stack Is Not Empty!" << endl;
			Display();
		}
	}
};
int main()
{
	Stack s;
	s.Push(1);
	s.IsEmpty();
	s.Pop();
	s.IsEmpty();

	return 0;
}

Here is what the above code is Doing:
1. We have created a class Stack.
2. We have created a private variable top which is a pointer to the node.
3. We have created a constructor which initializes the top to NULL.
4. We have created a function Push which takes an integer as an argument and pushes it to the stack.
5. We have created a function Pop which pops the top element from the stack.
6. We have created a function Top which displays the top element of the stack.
7. We have created a function Display which displays the whole stack.
8. We have created a function IsEmpty which checks if the stack is empty or not.
9. In the main function, we have created an object of the class Stack and called the functions.

Similar Posts