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

Controlled and Uncontrolled components in React

Chapter 5 Arrow Functions and Functional Style

A Vue Button Component with Confirm — Part 2

String to Object in JavaScript

7 array methods you should already know in JavaScript

VAR vs LET vs CONST: Scope’s Dilemma In A Nutshell

Data Dependencies Management in Redux Based Applications | 2

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

5. Connecting the dots — Big O and Queue Data Structure

source: Google images.

Types of Algorithms

A variable is an important and ubiquitous concept in programming.

Re rooting the Tree