Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6629935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:19:56+00:00 2026-05-25T22:19:56+00:00

I just finished working on this program but from the beginning I noticed that

  • 0

I just finished working on this program but from the beginning I noticed that it was somehow not printing out everything it was supposed to.
It’s needs to print the integers in a stack beginning from the top first and then do it again beginning from the bottom.
It prints the top to bottom correctly, but for some reason it only prints the very bottom number on the bottom to top.
for example if a stack contains the integers 1, 2, 3, 4, 5, 6,
where 1 is at the bottom of the stack and 6 is the top number.
the program should print the following:
Top { 6 5 4 3 2 1 } Bottom Bottom { 1 2 3 4 5 6 } Top

but it prints the following:
Top { 6 5 4 3 2 1 } Bottom Bottom { 1 } Top

here is the print function:

void Print() const     
// Prints stack contents to stdout in both top-to-bottom and bottom-to-top order 
{                      
  Node* temp = topPtr; 
  cout << "Top { ";

  // Forward print
  while (temp != NULL)
  {
    cout << temp->data << " "; 

    if (temp->next == NULL)
      break; 

    temp = temp->next;
  }
  cout << "} Bottom      Bottom { ";

  // Reverse print
  while (temp != NULL)
  {
    cout << temp->data << " ";  
    temp = temp->previous;
  }
  cout << "} Top" << endl;
} // End Print()

}; // End Class Stack

and If you need any further reference here is the main()

#include <iostream>
#include <fstream>
#include <new>
#include <cstddef>
#include "stack.h"

using namespace std;

int main(int argc, char* argv[])
{
   ifstream inputs;                  // Input file for commands
   char op;                              // Hold operation and        optional char input
  int value;                        // Value input from file
  string comment;                   // Holds comment from file
  Stack* sPtr = NULL;                  // Will point to stack object

  // Output usage message if one input file name is not provided
  if (argc != 2)
      {
        cout << "Usage:\n  project03  <inputfile>\n";
    return 1;
  }

  // Attempt to open input file -- terminate if file does not open
  inputs.open(argv[1]);
  if (!inputs)
  {
    cout << "Error - unable to open input file" << endl;
return 1;
  }

  // Input and echo header comment from file
  getline(inputs, comment);          // Input and echo the comment appearing in the test   file
  cout << endl << '#' << comment << endl;   

  // Process commands from input file
  inputs >> op;                     // Attempt to input first command
  while (inputs)
  {
    switch (op)                     // Process operation input from file
    {
      case '#':  // Test file comment
                 getline(inputs, comment);     // Input and echo the comment appearing in the test file
             cout << '#' << comment << endl;
             break;

  case 'c':  // Constructor
             cout << endl << "Stack( )";
             try
             {
               sPtr = new Stack( );    // Attempt to create an empty stack object
               cout << " -- Successful" << endl;
             }
             catch ( std::bad_alloc )
             {
               cout << "Failed : Terminating now..." << endl;
               return 1;
             }
             break;

  case '+':  // Push
             inputs >> value;
             cout << "Push(" << value << ")";
             try
             {
               sPtr->Push(value);
               cout << " -- successful";
             }
             catch (StackFull)
             {
               cout << " -- Failed Full Stack"; 
             }
             cout << endl;
             break;

  case '-':  // Pop
             cout << "Pop() -- ";
             try
             {
               sPtr->Pop();
               cout << "successful";
             }
             catch (StackEmpty)
             {
               cout << "Failed Empty Stack";
             }
             cout << endl;
             break;

  case 'f':   // IsFull
             cout << "IsFull() -- ";
             try
             {
                if (sPtr->IsFull())
                  cout << "true";
                else
                  cout << "false";
             }
             catch ( ... )
             {
               cout << "operation failed";
             }
             cout << endl;
             break;

  case 'e':   // IsEmpty
             cout << "IsEmpty() -- ";
             try
             {
                  if (sPtr->IsEmpty())
                       cout << "true";
                  else
                       cout << "false";
             }
             catch ( ... )
             {
                  cout << "operation failed";
             }
             cout << endl;
             break;

  case 'm':   // Make Empty
             sPtr->MakeEmpty();
             cout << "MakeEmpty()" << endl;
             break;         

  case 'p':  // Print Stack
             cout << "Print() -- ";
             sPtr->Print(); 
             break;

  case 't':  // Top of Stack
             try
             {
               cout << "Top() -- " << sPtr->Top() << endl;
             }
             catch (StackEmpty)
             {
               cout << "Top() -- Failed Empty Stack" << endl;
             }
             break;

  case '>':   // Max value within Stack
             try
             {
                  cout << "Max() -- " << sPtr->Max() << endl;
             }
             catch (StackEmpty)
             {
                  cout << "Max() -- Failed Empty Stack" << endl;
             }
             break; 

  case '<':   // Min value within Stack
             try
             {
                  cout << "Min() -- " << sPtr->Min() << endl;
             }
             catch (StackEmpty)
             {
                  cout << "Min() -- Failed Empty Stack" << endl;
             }
             break; 

  case '?':  // Peek(n) Stack
             inputs >> value;
             try
             {
               cout << "Peek(" << value << ") -- " << sPtr->Peek(value) << endl;  
             }
             catch (StackInvalidPeek)
             {
               cout << "Peek(" << value << ") -- Failed Invalid Peek" << endl;
             }
             break;

  case 's':  // Size of Stack
             cout << "Size() -- " << sPtr->Size() << endl;  
             break;

  case 'd':  // Destructor
             delete sPtr;
             sPtr = NULL;
             cout << "~Stack()" << endl << endl;
             break;

  default:   // Error
             cout << "Error - unrecognized operation '" << op << "'" << endl;
             cout << "Terminating now..." << endl;
             return 1;
             break;
}

inputs >> op;   // Attempt to input next command
 }

  return 0;
} // End main()

and here is header file for stack.cpp (stack.h)

//
// stack.h
//
// Specification file for Stack class, a stack of integers implemented
// using doubly-linked nodes.
//
// ***** DO NOT MODIFY THIS FILE *****
 //
#include <iostream>
using namespace std;


#ifndef STACK_H
#define STACK_H

class StackEmpty        {  /* No Code */  };
// StackEmpty exception class - throw an object of this type when stack is empty
// Hint: there is no code for exception classes

class StackFull         {  /* No Code */  };
// StackFull exception class - throw an object of this type when stack is full

class StackInvalidPeek  {  /* No Code */  };
// StackInvalidPeek exception class - throw an object of this type when invalid peek    position is used


struct Node                // Node data type for storing a single stack entry along with   pointers to
{                          // neighboring entries (previous and next) in the stack
  Node* previous;          // Member variable that holds the address of the predessor node in the stack sequence
  Node* next;              // Member variable that holds the address of the successor node in the stack sequence
  int   data;              // Member variable that holds the data value
};


class Stack                // Implements stack of integers ADT using doubly-linked sequence of nodes
{
  private:
  Node* topPtr;          // Points to the top node on the stack array

 public:
Stack();               // Default constructor initializes empty stack


~Stack();              // Destructor deallocates all nodes from stack 
                       // Must not create a memory leak

void Push(int n);      // Pushes integer n onto top of stack.  
                       // If unable to push, throws StackFull exception.

void Pop();            // Removes top integer from stack
                       // If stack is already empty, throws StackEmpty exception

bool IsEmpty() const;  // Returns true if stack is empty; false otherwise


bool IsFull() const;   // Returns true if stack is full; false otherwise


void MakeEmpty();      // Removes all nodes from stack leaving an empty, but usable stack
                       // Must not create a memory leak

int Top() const;       // Returns value of top integer on stack WITHOUT modifying the stack
                       // If stack is empty, throws StackEmpty exception

int Size() const;      // Returns number of items on stack WITHOUT modifying the stack


int Max() const;       // Returns value of largest integer within stack WITHOUT modifying the stack
                       // If stack is empty, throws StackEmpty

int Min() const;       // Returns value of smallest integer within stack WITHOUT modifying the stack
                       // If stack is empty, throws StackEmpty

int Peek( int n) const; // Returns stack value n levels down from top of stack. Peek(0) = Top()
                         // If position n does not exist, throws StackInvalidPeek


    .   ./*******  DO NOT MODIFY ANY OF THE CODE FOR PRINT()             *******/
/******   DO NOT PLACE A COPY OF PRINT() CODE IN STACK.CPP!!!   *******/

void Print() const     
// Prints stack contents to stdout in both top-to-bottom and bottom-to-top order 
{                      
  Node* temp = topPtr; 
  cout << "Top { ";

  // Forward print
  while (temp != NULL)
  {
    cout << temp->data << " "; 

    if (temp->next == NULL)
      break; 

    temp = temp->next;
  }
  cout << "} Bottom      Bottom { ";

  // Reverse print
  while (temp != NULL)
  {
    cout << temp->data << " ";  
    temp = temp->previous;
  }
  cout << "} Top" << endl;
} // End Print()

};  // End Class Stack

#endif

and finally here is stack.cpp which is the file I created the rest was given.

//
//  stack.cpp
//  
//
//  Created by Otapia on 9/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include <iostream>
#include <new>
#include "stack.h"

Stack::Stack()          // Default constructor initializes empty stack
{
topPtr = NULL;
}

Stack::~Stack()         // Destructor deallocates all nodes from stack 
                    // Must not create a memory leak
{
Node* tempPtr;
while ( topPtr != NULL ) 
{
tempPtr = topPtr;
topPtr = topPtr->next;
delete tempPtr;
}
}

void Stack::Push(int n) // Pushes integer n onto top of stack.  
                    // If unable to push, throws StackFull exception.
{
if(!IsFull())
{

 Node* tempPtr = new Node;
 tempPtr->data = n;
 tempPtr->next = topPtr;
 topPtr = tempPtr;

}
else
throw IsFull();
}

void Stack::Pop()       // Removes top integer from stack
                    // If stack is already empty, throws StackEmpty exception
{
    if (!IsEmpty())
    {
   Node* tempPtr;
  tempPtr = topPtr;
  topPtr = topPtr->next;
  delete tempPtr;
}
else
throw StackEmpty();
}

bool Stack::IsEmpty() const // Returns true if stack is empty; false otherwise
{

    return(topPtr == NULL);

}

bool Stack::IsFull() const  // Returns true if stack is full; false otherwise
{

Node* location;
try
{
location = new Node;
delete location;
return false;
} 
catch(std::bad_alloc) 

{return true; }

}

void Stack::MakeEmpty() // Removes all nodes from stack leaving an empty, but usable stack
                    // Must not create memory leak
{

    Node* tempPtr;
    while ( topPtr != NULL ) {
    tempPtr = topPtr;
    topPtr = topPtr->next;
    delete tempPtr;
}
  topPtr = NULL;

}

int Stack::Top() const  // Returns value of top integer on stack WITHOUT modifying the stack
{   
if(!IsEmpty())
return topPtr->data;


throw StackEmpty();
}

int Stack::Size() const // Returns number of items on stack WITHOUT modifying the stack
{

Node* temp = topPtr;
int count = 0;
while (temp != NULL)
{
temp = temp->next;
count ++;
}
return count;

}

int Stack::Max() const  // Returns value of largest integer within stack WITHOUT modifying the stack
                    // If stack is empty, throws StackEmpty
{
int max = 0;
int n;
Node* temp = topPtr;
  if(!IsEmpty())
{
while(temp != NULL)
{
n = temp->data;
if(n > max)
{
max = n;
}
temp = temp->next;
}
return max;}

else 
throw StackEmpty();
}

int Stack::Min() const  // Returns value of smallest integer within stack WITHOUT modifying the stack
                    // If stack is empty, throws StackEmpty
{int min = 100;
int n;
Node* temp = topPtr;
  if(!IsEmpty())
{
while(temp != NULL)
{
n = temp->data;
if(n < min)
{
min = n;
}
temp = temp->next;
}
return min;}

else 
throw StackEmpty();
}

int Stack::Peek(int n) const    // Returns stack value n levels down from top of stack.     Peek(0) = Top()
                            // If position n does not exist, throws StackInvalidPeek
{

int num = 0;
int x = 0;
Node* temp = topPtr;
   if(!IsEmpty())
{
while(temp != NULL)
{

if (x >= n || temp->next == NULL)
 break;
 temp = temp->next;

x++;
}
if (n <= x)
{
num = temp->data;
}
else throw StackInvalidPeek();

}
else
throw StackInvalidPeek();
return num;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T22:19:57+00:00Added an answer on May 25, 2026 at 10:19 pm

    Simple.

    while (temp != NULL)
    {
      cout << temp->data << " ";  
      temp = temp->previous;
    }
    

    From your problem description, and the error’d code, I’d assume temp->previous is incorrect. I assume this gets set in some sort of push function.

    void Stack::Push(int n) // Pushes integer n onto top of stack.  
                    // If unable to push, throws StackFull exception.
    {
      if(!IsFull())
      {
        Node* tempPtr = new Node;
        tempPtr->data = n;
        tempPtr->next = topPtr;
        topPtr = tempPtr;    
      } else
        throw IsFull();
    }
    

    You never set previous, so it’s left as some unspecified value (of zero). Also, previous is not set or checked anywhere in your cpp file. It should be set here, although really doesn’t need to be anywhere else.

    Lastly, throw IsFull() is a heck of an exception. You probably didn’t mean to throw the bool result of a function call.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I just finished working out a memory allocation problem with the current program I'm
Just finished reading this blog post: http://www.skorks.com/2010/03/an-interview-question-that-prints-out-its-own-source-code-in-ruby/ In it, the author argues the case
I'm just about finished my first release of automailer, a program I've been working
I just finished working on a webapp of mine that will have lots of
I've just finished working for a client which has burnt millions on a project
I just recently finished Michael Feathers' book Working Effectively with Legacy Code . It
Just finished read this post by Greg Young, where he is talking about Microsoft
I just finished a small project where changes were required to a pre-compiled, but
I just finished a medium sized web site and one thing I noticed about
I just finished setting up an out-of-place build system for our existing C++ code

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.