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

Stacks can be easily implemented using a linked list. Stack is a data structure to which a data can be added using the push( ) method and data can be removed from it using the pop( ) method. With Linked list, the push operation can be replaced by the add at front method of linked list and pop operation can be replaced by a function which deletes the front node of the 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;
}

--

--

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