Skip to content

Instantly share code, notes, and snippets.

@lsiddiqsunny
Created September 6, 2017 19:16
Show Gist options
  • Save lsiddiqsunny/7057c20ce67971f935b0b6b269958332 to your computer and use it in GitHub Desktop.
Save lsiddiqsunny/7057c20ce67971f935b0b6b269958332 to your computer and use it in GitHub Desktop.
#include<bits/stdc++.h>
using namespace std;
template<typename T>
struct linkedlist
{
T data;
linkedlist *next;
};
template<typename T>
class Stack
{
T data;
linkedlist<T> *root;
int Size;
public:
Stack()
{
root=NULL;
Size=0;
}
void push(T data)
{
Size++;
if(root==NULL)
{
root=new linkedlist<T>;
root->data=data;
root->next=NULL;
return;
}
linkedlist<T> *temp=new linkedlist<T>;
temp->data=data;
temp->next=root;
root=temp;
}
T pop()
{
if(root==NULL)
{
cout<<"UNDERFLOW\n";
return INT_MIN;
}
else if(root->next==NULL)
{
T x=root->data;
Size--;
root=NULL;
return x;
}
else
{
T x=root->data;
Size--;
root=root->next;
return x;
}
}
T top(){
return root->data;
}
int size()
{
return Size;
}
void print()
{
linkedlist<T> *c_node=root;
while(c_node!=NULL)
{
cout<<c_node->data<<" ";
c_node=c_node->next;
}
cout<<endl;
}
};
int main()
{
Stack<int> s;
s.push(3);
//s.print();
s.push(43);
// s.print();
s.push(31);
// s.print();
cout<<s.top()<<endl;
s.print();
s.pop();
s.print();
s.pop();
s.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment