Introduction To Stack
Introduction To Stack
Stack of Books
¢ Its uses span the spectrum from reversing items to depth-first searches in artificial intelligence
applications to keeping track of function calls
¢ It can be implemented using either a linked list or a one-dimensional array.
¢ The following code implements a stack using a linked list
¢ Note that it currently only accepts integers. A more useful stack could be created by using a
templated class (remember templated functions?)
Code
//This program implements a stack using a linked list. Note that a stack can also be
implemented using an array
#include "stdafx.h"
#include<iostream>
struct node
int data;
};
class stack
private:
public:
stack() // constructor
top=NULL;
};
// PUSH Operation
void stack::push()
int value;
cout<<"\nPUSH Operation\n";
cin>>value;
ptr=new node;
ptr->data=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
// POP Operation
void stack::pop()
if(top==NULL)
return;
temp=top;
top=top->next;
delete temp;
}
// Show stack
void stack::show()
while(ptr1!=NULL)
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
cout<<"NULL\n";
// Main function
int main()
stack s;
int choice;
while(1)
cout<<"\n-----------------------------------------------------------";
cin>>choice;
switch(choice)
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
exit(0);
break;
default:
break;
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <stack>
#include <string>
int main()
cin>>word;
allwords.push(word);
while (!allwords.empty())
{
cout << allwords.top() << endl;
return 0;
Member Functions