Solved

C++ program

Posted on 1998-10-04
4
190 Views
Last Modified: 2011-09-20
This program will push and pop consecutive numbers from one to ten. How can I change it to push (ie.1,100,and 4),print the stack of integers. Then, pop (ie. 4),push (ie. 7,-9)and prints the stack again. Finally, pops all the values on the stack, and print the stack. Do you think I should use an array in the stack?

 
// This is the header file
#ifndef TSTACK1_H
#define TSTACK1_H

#include <iostream.h>

template< class T >
class Stack {
public:
   Stack( int = 10 );    // default constructor (stack size 10)
   ~Stack() { delete [] stackPtr; } // destructor
   bool push( const T& ); // push an element onto the stack
   bool pop( T& );        // pop an element off the stack
private:
   int size;             // # of elements in the stack
   int top;              // location of the top element
   T *stackPtr;          // pointer to the stack

   bool isEmpty() const { return top == -1; }      // utility
   bool isFull() const { return top == size - 1; } // functions
};

// Constructor with default size 10
template< class T >
Stack< T >::Stack( int s )
{
   size = s > 0 ? s : 10;  
   top = -1;               // Stack is initially empty
   stackPtr = new T[ size ]; // allocate space for elements
}

// Push an element onto the stack
// return 1 if successful, 0 otherwise
template< class T >
bool Stack< T >::push( const T &pushValue )
{
   if ( !isFull() ) {
      stackPtr[ ++top ] = pushValue; // place item in Stack
      return true;  // push successful
   }
   return false;     // push unsuccessful
}

// Pop an element off the stack
template< class T >
bool Stack< T >::pop( T &popValue )
{
   if ( !isEmpty() ) {
      popValue = stackPtr[ top-- ];  // remove item from Stack
      return true;  // pop successful
   }
   return false;     // pop unsuccessful
}

#endif

// This is the main program
#include <iostream.h>
#include "tstack1.h"

int main()
{
   Stack< double > doubleStack( 5 );
   double f = 1.1;
   cout << "Pushing elements onto doubleStack\n";

   while ( doubleStack.push( f ) ) { // success true returned
      cout << f << ' ';
      f += 1.1;
   }

   cout << "\nStack is full. Cannot push " << f
        << "\n\nPopping elements from doubleStack\n";

   while ( doubleStack.pop( f ) )  // success true returned
      cout << f << ' ';

   cout << "\nStack is empty. Cannot pop\n";

   Stack< int > intStack;
   int i = 1;
   cout << "\nPushing elements onto intStack\n";

   while ( intStack.push( i ) ) { // success true returned
      cout << i << ' ';
      ++i;
   }

   cout << "\nStack is full. Cannot push " << i
        << "\n\nPopping elements from intStack\n";

   while ( intStack.pop( i ) )  // success true returned
      cout << i << ' ';

   cout << "\nStack is empty. Cannot pop\n"<< endl;

   return 0;
}
0
Comment
Question by:nelsonab
4 Comments
 

Expert Comment

by:eric_m
ID: 1174340
I'd suggest using the STL stack.

#include <stack>

But then, that's the easy way.  :)

0
 
LVL 5

Expert Comment

by:scrapdog
ID: 1174341
I would suggest using a linked list instead of an array.  A linked list would not limit the stack size.



// This is the header file
#ifndef TSTACK1_H
#define TSTACK1_H

#include <iostream.h>

struct StackNode
  {
       int Value;
       StackNode *Prev;
  };

class Stack {
public:
      Stack( int = 10 );    // default constructor (stack size 10)
      ~Stack() { StackNode *current, *prevnode;
                          current = StackPtr;
                          while (current != NULL)
                               {
                                     prevnode = current->Prev;
                                     delete current;
                                     current = prevnode;
                                } // destructor
                         }
      bool push( int pushValue ); // push an element onto the stack
      bool pop( int popValue );        // pop an element off the stack
private:
      StackNode *stackPtr;          // pointer to the stack

      bool isEmpty() const { return StackPtr == NULL; }      // utility
};

// Constructor with default size 10
Stack::Stack();
{
      stackPtr = NULL; // allocate space for elements
}

// Push an element onto the stack
// return 1 if successful, 0 otherwise

bool Stack::push( int pushValue )
{
      StackNode *newstackNode;
      newstackNode = new StackNode;
      newstackNode->Prev = stackPtr;
      stackPtr = newStackNode;
      stackPtr->Value = pushValue;
      return true;  // push successful
}

// Pop an element off the stack

bool Stack::pop( int popValue )
{
      StackNode *prevstackPtr;
      if ( !isEmpty() ) {
            popValue = stackPtr->Value;
            prevStackPtr = stackPtr->Prev;
            delete StackPtr;
            StackPtr = prevStackPtr;
            return true;  // pop successful
      }
      return false;     // pop unsuccessful
}



Don't take this code literally because I know almost nothing about C++ (I only know a little bit about C).  I took out the template thingamajigs, because I don't know how to use them :)

But, hopefully you can see what it is doing.  It (is supposed to) dynamically allocate nodes in the stack.  The StackPtr will always point to the top of the stack.  Pushing will allocate new memory, and popping will deallocate it.


scrapdog
0
 
LVL 2

Expert Comment

by:gysbert1
ID: 1174342
The only problem I can see is printing the stack !

Pushing and popping like you describe can be done by simply calling push and pop each time as in the example (except, the example pushed everthing and then popped everything).

It is not possible to print the stack with this code, you do not have access to variables in the stack, you have to remove (pop) them to know what they are. You have three options in printig the stack.

1) Return the stackPtr (thus make it public).
   This is generally a bad idea since you can mess up the stack.
2) Write a function that returns an element in the stackPtr (peek).
  eg:

// Peek into the stack at Position
Template< class T >
    bool Stack< T >::peek( T &peekValue , int Position)
    {
      if (top> Position) {
          peekValue = stackPtr [Position];  // Peek stack value
          return true;  // peek successful
      }
      return false;     // peek unsuccessful
    }

3) Add a function to the stack that prints the contents (usefull if you want to see it only but the results is the of course not accessible ...
0
 
LVL 8

Accepted Solution

by:
Answers2000 earned 50 total points
ID: 1174343
1. To (be capable) of printing all items in the stack you need a function in the stack class that will go thru the stack printing all items without popping anything

(i) Add prototype for this function to the class (should be a public function so can easily be called)

template< class T >
class Stack {
public:
//etc
void PrintStack() const ;
//etc
} ;

(ii) Definition for the function

template< class T >
void Stack< T >::PrintStack() const
{
  T * pTemp = stackPtr ;

  int x = 0 ;

  while ( x <= top )
  {
     cout << pTemp << "\n" ;
     pTemp++ ;
     x++ ;
  }
}

You can modify the direction of the loop if you want to print the stack in the other order.  Modify the cout line if you want to print the items with a different layout.


2. >>How can I change it to push (ie.1,100,and 4),print the stack of integers. Then, pop (ie. 4),push (ie. 7,-9)and prints the stack again.

Modify the code in main to do this

int main()
{
   Stack< double > doubleStack( 5 );

   cout << "Pushing 1, 100, 4" ;
   
   doubleStack.push( 1.0 ) ;
   doubleStack.push( 100.0 ) ;
   doubleStack.push( 4.0 ) ;
 
   cout << "Stack now contains\n" ) ;
   doubleStack.PrintStack() ;

   double temp2 ;
   doubleStack.pop( temp ) ;
   cout << "Popped an item, value is " << temp2 << "\n" ;

   cout << "Pushing 7 and -9\n" ;
   doubleStack.push(7) ;
   doubleStack.push(-9) ;

   cout << "Stack now contains\n" ) ;
   doubleStack.PrintStack() ;

   return 0 ;
}


3. >> Do you think I should use an array in the stack?

I think you should use the Standard (Template) Library [STL] to do the stack.  Their is a built in class called stack which will do a variable size stack.  If you don't have STL available to you then this is a reasonable explanation.

The problem with an array is that it specifies when the class is created how many items are in the stack.  This means you can easily run out later, or can allocate items that are never used (e.g. default stack size is 10, you might only use a few items) which is a bit wasteful.

Whether it's worth caring about this "waste" is up to you.  For a simple program like this it probably doesn't matter.  If a program with hundreds of stack objects or highly variable stack size (it might contain 1 item or 1,000,000) then it probably would matter.

Using a linked list, or the STL vector class if you want a variable size list.

If the STL vector class is not available to you for some reason you could also use a template based array class (that you create yourself) and supports variable size lists, as the basis for your stack implementation





0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now