Skip to content

Instantly share code, notes, and snippets.

@na5imuzzaman
Created July 17, 2017 19:27
Show Gist options
  • Save na5imuzzaman/07e065cdb1a731d4aaac229d12f13bb2 to your computer and use it in GitHub Desktop.
Save na5imuzzaman/07e065cdb1a731d4aaac229d12f13bb2 to your computer and use it in GitHub Desktop.
Stack Implementation in c++ (without using stack from STL)
/* Nasim */
#include<iostream>
#include<cstdlib>
using namespace std;
class node
{
public:
int data;
node *next;
};
node* getNewNode(int n)
{
node *root = new node();
root->data = n;
root->next = NULL;
return root;
}
void push(int n,node **top)
{
node *root = getNewNode(n);
root->next = (*top);
(*top) = root;
}
void pop(node **top)
{
node *temp = (*top);
(*top) = (*top)->next;
delete temp;
}
void print(node *head)
{
node *root = head;
while(root != NULL)
{
cout<<root->data<<" ";
root = root->next;
}
cout<<"\n";
cout<<"\n";
}
void print_delete(node *head)
{
node *root = head;
while(root != NULL)
{
cout<<root->data<<" ";
node *temp = root;
root = root->next;
delete temp;
}
cout<<"\n";
}
int main()
{
node *top = NULL;
push(352,&top);
print(top);
push(322,&top);
print(top);
push(312,&top);
print(top);
push(342,&top);
print(top);
pop(&top);
print(top);
pop(&top);
print(top);
push(0,&top);
print_delete(top);
print(top); //Garbage Value
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment