LINKED LIST IMPLEMENTATION OF STACK
Write
a program to implement a LINKED STACK which stores Book’s information.
//Program
to implement a Linked Stack
#
include < iostream . h >
#
include < process . h >
#
include < stdio . h >
#
include < conio . h >
struct
Book
{
int bookid ;
char bookname [ 30 ] ;
Book *next ;
} ;
class
Stack
{
Book *top ;
public :
Stack ( )
{
top = NULL ; //denotes stack is empty
}
void Push( )
{
Book *newnode = new Book ;
if ( newnode == NULL )
{
cout << "Not enough memory " ;
getch ( ) ;
return ;
}
cout << "\nEnter the Book id and Book name ::" ;
cin >> newnode -> bookid
;
gets ( newnode ->bookname ) ;
newnode -> next = NULL ;
if ( top ==NULL )
top = newnode ;
else
{
newnode -> next = top ;
top = newnode ;
}
cout << "\n Book Added" ;
}
void Pop( )
{
if(top == NULL )
{
cout << "\nStack
is empty !" ;
getch( );
return;
}
cout << "Popped element is ::\n";
cout << top -> bookid
<< " "
<< top -> bookname;
Book * temp = top;
top = top -> next ;
delete temp ;
}
void display ( )
{
if(top == NULL )
{
cout << "\nStack
is empty !" ;
getch( );
return;
}
cout << "\n Stack contents are ....\n"
;
Book *ptr = top ;
while ( ptr )
{
cout << ptr -> bookid << " "
<< ptr -> bookname
<<endl ;
ptr = ptr -> next ;
}
}
} ;
void
main()
{
clrscr ( ) ;
Stack S ;
int ch ;
while ( 1 )
{
cout << "\n1. Push an element" ;
cout << "\n2. Pop an element" ;
cout << "\n3. Display the stack" ;
cout << "\n4. Exit" ;
cin >> ch ;
switch ( ch )
{
case 1 :
S.Push ( )
;
break ;
case 2 :
S.Pop ( )
;
break ;
case 3 :
S.display
( ) ;
break ;
case 4 :
exit ( 0 )
;
}
getch( ) ;
}
}
No comments:
Post a Comment