stack using singly linked list code example
Example 1: implement stack using link list in c
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
struct node
{
int data;
struct node *next;
};
typedef struct node node;
node *top;
void initialize()
{
top = NULL;
}
void push(int value)
{
node *tmp;
tmp = malloc(sizeof(node));
tmp -> data = value;
tmp -> next = top;
top = tmp;
}
int pop()
{
node *tmp;
int n;
tmp = top;
n = tmp->data;
top = top->next;
free(tmp);
return n;
}
int Top()
{
return top->data;
}
int isempty()
{
return top==NULL;
}
void display(node *head)
{
if(head == NULL)
{
printf("NULL\n");
}
else
{
printf("%d\n", head -> data);
display(head->next);
}
}
int main()
{
initialize();
push(10);
push(20);
push(30);
printf("The top is %d\n",Top());
pop();
printf("The top after pop is %d\n",Top());
display(top);
return 0;
}
Example 2: stack using linked list
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class Node {
public:
T data;
Node<T> *next;
Node(T data) : data(data), next(NULL) {}
};
template <typename T>
class Stack {
Node<T> *head;
int size{0};
public:
Stack() {
head = NULL;
size = 0;
}
int getSize() { return size; }
bool isEmpty() {
if (head == NULL) {
return true;
}
return false;
}
void push(int data) {
Node<T> *temp = new Node<T>(data);
temp->next = head;
head = temp;
size++;
}
void pop() {
if (head == NULL) {
cout << "==============" << endl;
cout << "STACK EMPTY!!!" << endl;
cout << "==============" << endl;
return;
}
Node<T> *temp = head;
head = head->next;
temp->next = NULL;
delete temp;
size--;
}
T top() {
if (head == NULL) {
cout << "==============" << endl;
cout << "STACK EMPTY!!!" << endl;
cout << "==============" << endl;
return 0;
}
return head->data;
}
};
int main() {
Stack<int> s;
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
cout << s.getSize() << endl;
cout << s.top() << endl;
s.pop();
}