Linked List Implementation of Stack

  • push: push an element into the stack
  • pop: remove the last element added
  • top: returns the element at top of the stack

Implementation of Stack using Linked List

class node
{
int data;
node *next;
};
class Stack
{
node *front; // points to the head of linked list
public:
Stack()
{
front = NULL;
}
void push(int); //add an element
void pop(); //remove an element
int top(); // return top element
};
void Stack :: push(int d)
{
node *temp; // creating a new node
temp = new node();
temp->data = d; // setting data to it

// add the node in front of list
if(front == NULL)
{
temp->next = NULL;
}
else
{
temp->next = front;
}
front = temp;
}
void Stack :: pop()
{
if(front == NULL) // if empty
cout << "UNDERFLOW\n";

// delete the first element
else
{
node *temp = front;
front = front->next;
delete(temp);
}
}
int Stack :: top()
{
return front->data;
}

--

--

--

2nd Year CSE UnderGraduate

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

JSON Serialization for Server-Client Communication in “Warring States”

Getting Started with React Testing Library

20 best courses to learn Vue JS on YouTube

Why Choose Gridsome Over VuePress or Nuxt

Difference between let, const and var in easiest way with Guarantee…

Node.js V8 internals: an illustrative primer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Megha Agarwal

Megha Agarwal

2nd Year CSE UnderGraduate

More from Medium

Dijkstra Algorithm

Concurrency control

Shared Vision

Time (part 2):