stack implementation using linked list in cpp
Stack Implementation Using Linked List in C++
A stack is a data structure that follows the LIFO (Last-In-First-Out) principle. In this implementation, we will use a linked list to create a stack in C++.
Here are the steps to implement a stack using a linked list:
- Define the Node Structure: We need to define a structure for the nodes of the linked list. Each node should contain two parts: a data element and a pointer to the next node.
struct Node {
int data;
Node* next;
};
- Initialize the Top Pointer: We need a pointer to keep track of the top element of the stack. Initially, this pointer should be set to
NULL
to indicate an empty stack.
Node* top = NULL;
- Push Operation: To insert an element into the stack, we create a new node and update the
next
pointer to point to the previous top node. Then, we update thetop
pointer to point to the new node.
void push(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = top;
top = newNode;
}
- Pop Operation: To remove an element from the stack, we update the
top
pointer to point to the next node. We also need to free the memory occupied by the node that we are removing.
void pop() {
if (top == NULL) {
cout << "Stack is empty." << endl;
return;
}
Node* temp = top;
top = top->next;
delete temp;
}
- Top Operation: To retrieve the top element of the stack without removing it, we can simply return the data element of the
top
node.
int topElement() {
if (top == NULL) {
cout << "Stack is empty." << endl;
return -1; // or any other appropriate value to indicate an empty stack
}
return top->data;
}
- Empty Operation: To check if the stack is empty, we can simply check if the
top
pointer isNULL
.
bool isEmpty() {
return (top == NULL);
}
That's it! You have successfully implemented a stack using a linked list in C++. Now you can use the push
, pop
, topElement
, and isEmpty
functions to perform stack operations.
Let me know if you have any further questions.