Stack using Linked List
itsLu
c_cpp
2 years ago
1.8 kB
13
Indexable
//constructor, push, pop, isEmpty, getNumberOfElements, displayData, deleteStack, destructor
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class LinkedStack
{
node *top;
public:
LinkedStack()
{
top = NULL;
}
void push(int data)
{
node *item = new node;
item->data = data;
item->next = top;
top = item;
}
bool isEmpty ()
{
return top == NULL;
}
int pop()
{
if (isEmpty())
{
cout << "Stack is empty!\n";
return -1;
}
node *temp = top;
int tempData = temp->data;
top = top->next;
delete temp;
return tempData;
}
int getNumberOfElements()
{
int counter = 0;
node *temp;
for (temp = top ; temp != NULL ; temp = temp->next)
counter++;
return counter;
}
void displayStack()
{
node *temp;
for (temp = top ; temp != NULL ; temp = temp->next)
cout << temp->data << "\t";
}
void deleteStack()
{
node *temp;
while (top != NULL)
{
temp = top;
top = top->next;
delete temp;
}
}
~LinkedStack()
{
deleteStack();
cout << "\nStack is deleted!";
}
};
int main()
{
LinkedStack stack1;
for (int k = 2 ; k <= 16 ; k*=2)
stack1.push(k);
stack1.displayStack();
cout << endl;
cout << stack1.getNumberOfElements() << endl;
cout << stack1.pop() << "\t" << stack1.pop() << endl;
stack1.displayStack();
cout << endl;
cout << stack1.getNumberOfElements() << endl;
}
Editor is loading...
Leave a Comment