Need a project done?

C++ Programming Developer

Search This Blog

Stack using Link List in C++

Program to create a stack using link list in C++.

//Stack using Link List in C++
#include <iostream>
using namespace std;



class stack{
public:
stack();
void push(int);
void pop(int &);
bool isEmpty(void);

private:
struct node{
node(){ next = NULL; }
int data;
node* next;
}*top;

};
//--------------------------------------------------------
stack::stack(){
top = NULL;
}
//--------------------------------------------------------
void stack::push(int x){
//(insert at head (top))
node* newNode = new node;
newNode->data = x;

if (top != NULL){
newNode->next = top;
top = newNode;
}
else{
newNode->next = NULL;
top = newNode;
}

}
//--------------------------------------------------------
void stack::pop(int &x){
if (isEmpty()){
cout << "Stack is Empty" << endl;
}
else{
x = top->data;
node* temp = top;
top = top->next;
delete temp;
temp = NULL;
}
}
//--------------------------------------------------------
bool stack::isEmpty(void){
return top == NULL;
}
////////////////////////////////////////////////////
int main(){
stack obj;

for (int i = 1; i<=5; i++){
cout << "Pushing " << i << endl;
obj.push(i);
}

cout << "Popping..." << endl;
int x;
for (i = 1; i<=5; i++){
obj.pop(x);
cout << x << endl;
}


///////LETS DO IT AGAIN//////
for (i = 1; i<=5; i++){
cout << "Pushing " << i << endl;
obj.push(i);
}

cout << "Popping..." << endl;
for (i = 1; i<=5; i++){
obj.pop(x);
cout << x << endl;
}
return 0;
}
"Don't let anyone ever make you feel like you don't deserve what you want."