Stack Implementation In Dev C++ Using Linked List
Source Code:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node {
int data;
node *next;
};
node *head = NULL;
void push (int val) {
node *temp = new node();
//node *temp = (node*)malloc(sizeof(node));
temp->data = val;
temp->next = head;
head = temp;
}
void pop() {
if(head== NULL){
cout<<"Stack is empty"<<endl;
return;
}
cout<<head->data<<" is pop from stack"<<endl;
node *temp = head;
head = head->next;
delete temp;
}
void display() {
if(head == NULL) {
cout<<"Stack is Empty!...."<<endl;
return;
}
cout<<"Stack contains the following items:...."<<endl;
node *temp;
temp = head;
while(temp != NULL) {
cout<<temp->data<<" -> ";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
int main(int argc, char** argv) {
display();
push(30);
push(23);
push(56);
push(66);
display();
pop();
pop();
display();
push(100);
display();
pop();
return 0;
}
Output:
Working:
This programwill help us to understand stack implementation using C++. This source code is written using Dev-C++ code editor. Stack implementation using linked list provides a convinient way for managing dynamic size of stack. In this code example we use the follwoing functions/methods for various stack operations.
Sr. | Method/Function | Operation | Description |
1 | Push | Insertion | Add data item on top of the stack. |
2 | Pop | Remove | Retrive/remove data item from top of the stack. |
3 | Display | Show | Display all items currently stored in stack. |
As stack use LIFO order therefore we have to decide either to store and remove items from start or end of the stack. As there will be only one end for both operation.
Following two header files are included in program.
- #include <iostream>
- #include <stdlib.h>
First library is used for I/O operations and second library is included for dynamic memory allocation.
malloc is define in second header file.
For node structure we use struct that consist of two data members value and next. Value data part is used to store the node data and next part will store the address of next node. In practice in next part of each newly created node we store NULL.
In push operation we just create a new temp node and made this temp node as head as we uses head point for both push and pop operations.In pop operation we first check either stack is empty or not. If stack contain value then we have to remove the head value and make the next node as head. These two methods are mandatory in stack implementation.
The last method is display, this method is optional. Display method is define to view the current state of stack. We use a temp node to traverse and display all items store in the stack. we use here while loop as iterative structure.