Understanding ADT Stack

This is a discussion on Understanding ADT Stack within the C++ Programming forums, part of the General Programming Boards category; Hi. I am having trouble understanding and working with this ADT Stack implementation. For instance, how can you examine the ...

  1. #1
    diligentStudent()
    Join Date
    Apr 2002
    Posts
    79

    Understanding ADT Stack

    Hi. I am having trouble understanding and working with this ADT Stack implementation. For instance, how can you examine the top element in the stack when the function to do so accepts an argument? Same for the function to pop. It takes an argument. As you can see, about all I could do was push! Any ideas? Thanks, Steve
    Code:
    #include<iostream>
    using namespace std;
    
    template<class T>
    struct Node
    {
        T data;
        Node<T> *next;
    };
    
    template<class T>
    class Stack
    {
        private:
            int count;
            Node <T> *top;
        public:
            Stack();
            ~Stack();
            bool pushStack(T dataIn);
            bool popStack(T& dataOut);
            bool stackTop(T& dataOut);
            bool emptyStack();
            bool fullStack();
            int stackCount();
    };
    
    template<class T>
    Stack<T>::Stack()
    {
        top=NULL;
        count=0;
    }
             
    template<class T>
    bool Stack<T>::pushStack(T dataIn)
    {
        bool success;
        Node<T> *newPtr;
        
        if(!(newPtr = new Node<T>))
            success=false;
        else
        {
            newPtr->data=dataIn;
            newPtr->next=top;
            top=newPtr;
            count++;
            success=true;
        }
        return success;
    }
    
    template<class T>
    bool Stack<T>::popStack(T& dataOut)
    {
        Node<T> *dltPtr;
        bool success;
        
        if(count==0)
            success=false;
        else
        {
            dltPtr=top;
            dataOut=top->data;
            top=top->next;
            count--;
            success=true;
        }
        return success;
    }
    
    
    template<class T>
    bool Stack<T>::stackTop(T& dataOut)
    {
        bool success;
        
        if(count==0)
            success=false;
        else
        {
            dataOut=top->data;
            success=true;
        }
        return success;
    }        
    
    template<class T>
    bool Stack<T>::emptyStack()
    {
        return (count==0);
    }    
    
    template<class T>
    bool Stack<T>::fullStack()
    {
        Node<T> *temp;
        
        temp=new Node<T>;
        if(temp != NULL)
        {
            delete temp;
            return false;
        }
        return true;
    }        
    
    template<class T>
    Stack<T>::~Stack()
    {
        Node<T> *temp;
        
        while(top != NULL)
        {
            temp=top;
            top=top->next;
            delete temp;
        }
    }
    
    int main()
    {
        Stack<double> s;
        s.pushStack(45.33);
        return 0;
    }

  2. #2
    #include<xErath.h> xErath's Avatar
    Join Date
    Jun 2004
    Posts
    722
    Its very simple. All function returns a bool whether the action was possible to be performed or not (e.g. empty stack). And the elements you want to look for or pop are stored in the var that you send to the function. Notice that the arguments are references.
    When the funtion returns the var you sent is set with the value/state of the one you wanted.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Code:
    int main()
    {
        Stack<double> s;
        s.pushStack(45.33);
    
        double item;
        if (s.popStack(item))
            cout << item << endl;
    
        return 0;
    }
    Notice for popStack(), you are passing dataOut by reference:
    Code:
    bool Stack<T>::popStack(T& dataOut)
    This means if dataOut is modified in the function, main() will see it. Only if you pass by value is a copy made. A reference uses the argument's actual address.

    The same is true for stackTop().

  4. #4
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    Code:
    ...
    double item=0.0;
    s.stackTop(item);
    cout<<item;
    ...
    I think this is all you need to see what is on top.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

  5. #5
    diligentStudent()
    Join Date
    Apr 2002
    Posts
    79

    Thanks.

    If I told you that I understood it completely, I would not be telling the truth. Why do you have to supply a "dummy" variable to run this thing? I'm sure that there is a good reason, I just don't know it. Steve

  6. #6
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    The variable is not a dummy... it is the variable that holds the value "returned" by the function. In functions that want to return more than one piece of data, an argument is often passed by reference in order to get that data.

    In this case, stackTop wants to give you the value at the top of the stack (a double in your example) and at the same time tell you if there actually is anything available on the stack to return (a bool). To do this, it returns the bool from the function, and it sets the value of the passed in parameter to the value at the top of the stack.

    If you understand pass-by-reference, that should help you understand. If you don't, the basics are that you pass the variable by reference so that any changes made to the data for that variable inside the function are applied to the variable on the outside also. In this example, if item started out as 0.0, and the the stackTop function is called, then stackTop will set dataOut to 45.33. But since dataOut is only a reference to item, then item is also set to 45.33. When stackTop returns, item now has the correct value.

    The only reason pass-by-reference was used in this instance was in order to return two separate values to the caller, a bool and the double.

  7. #7
    diligentStudent()
    Join Date
    Apr 2002
    Posts
    79

    Starting to get a picture

    I really appreciate the information. As I said, I was at a loss. If Swoopy (thanks) didn't show me how to create an object (double item) to pass to the function, I wouldn't have had any idea of what to do next. I have some other ADT implementations that I am examining. Hopefully I will have a better idea from having completed this exercise. Steve

  8. #8
    Registered User
    Join Date
    Apr 2003
    Posts
    78

    try this algorithm dude

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <time.h>
    using namespace std;
    
    //===============================CLASSE DEFINITION FOR STACK============================================================
    
    
    
    template <class T, int n>
    class stack
    {
    	private: T elt[n];                                                  
    			 int counter;
    	public:
    		void clearstack() {  counter = -1;                             } //INITIALIZE COUNTER
    		bool emptystack() {  return counter==-1?true:false;            } //EVALUATION IF STACK IS EMPTY
            bool fullstack()  {  return counter== n-1?true:false;          } //EVALUATION IF STACK IS FULL
    		void push(T x)    {  counter++; elt[counter] = x;              } //FUNCTION TO ADD TO STACK
    		T pop()           {  T x; x= elt[counter]; counter--;return x; } //FUNCTION TO POP THE STACK
    };
    
    
    
    
    //======================================================================================================================
    
    
    
    int main()
    {
       
     
     int  q, m, p ;	            //THREE VARIABLES M Q AND P DECLARED FOR PUSH AND POP OPERATIONS 
     char j;				    //VARIABLE J TO DETERMINE WETHER TO CONTINUE PROGRAM OR NOT
     char k;		 		    //VARIABLE K TO DETERMINE TYPE OF OPERATION BINARY OCTAL OR HEXADECIMAL 
     char z; 					//VARIALBE Z TO USE IN HEXADECIMAL OPERATIONS SPECIFICALLY
     time_t t;
     time(&t);
     stack <int, 17> s;         //OBJECT OF STACK TYPE DECLARED
     while(j!='n')              //BEGINNING OF WHILE LOOP TO CONTINUE PROGRAM UNTIL VARIABLE J IS EQUAL TO 'n'
     {
    
    	 
    
     cout<<"===========================Conversion Menu================================"<<endl;
     cout<<"1.Decimal to binary"<<endl;
     cout<<"2.Decimal to octal"<<endl;
     cout<<"3.Decimal to hexadecimal"<<endl;
     cout<<"4.Exit"<<endl;
     cout<<"time and date is"<<ctime(&t);
     cin>>k;                   //REQUEST TO USER TO ENTER THE TYPE OF OPERATION
     
     switch(k)                 //SWITCH STATEMENT USED TO RUN TYPE OF OPERATION CHOSEN BY USER
     {
     //======================================================================================================================= 
    	 case '1':             //CASE 1 FOR BINARY OPERATIONS
      
    	 s.clearstack(); 
    	 
    	 cout<<"Enter a number to convert: ";
    	 cin>>m;
    	 
    	 while( m!=0 &&!s.fullstack() )
    		{
    		 q = m % 2;        
    		 s.push(q);
    		 m =	m / 2;
    		}	
     
    	 while(!s.emptystack())
    		{
    		 p = s.pop();	
    		 cout<<p;
    		}
    	cout<<"\nPRESS 'y' TO CONTINUE: ";
    	cin>>j;
    	while(j !='y')
    	{
    	cout<<"\nYou entered an invalid response:";
    	cout<<"\nPlease re-enter your choice: "; 
    	cin>>j;
    	}
    
    	 break;
    //=======================================================================================================================
    	case '2':               //CASE 2 FOR OCTAL OPERATIONS
     
    	s.clearstack(); 
    	 cout<<"Enter a number to convert: ";
    	 cin>>m;
    	 while( m!=0 &&!s.fullstack() )
    		{
    		 q = m % 8;
    		 s.push(q);
    		 m =	m / 8;
    		}	
     
    	 while(!s.emptystack())
    		{
    		 p = s.pop();	
    		 cout<<p;
    		}
    		cout<<"\nPRESS 'y' TO CONTINUE: ";
    	cin>>j;
    	while(j !='y')
    	{
    	cout<<"\nYou entered an invalid response:";
    	cout<<"\nPlease re-enter your choice: "; 
    	cin>>j;
    	}
    
    	 break;
    
    
    //=======================================================================================================================
    	case '3':                              //CASE 3 FOR HEXADECIMAL OPERATIONS
    
    	 s.clearstack(); 
    	 cout<<"Enter a number to convert: ";
    	 cin>>m;
    	while( m!=0 &&!s.fullstack() )
    	{
    	 z = m % 16;
    				 if(z<10 || z>15)         //IF STATEMENT TO DETERMINE WETHER OR NOT CHAR OR INT VALUE DISPLAYED
    				 {
    	 				s.push(z);m = m / 16;
    				 }			
    	 
    			else if(z>=10 || z<=15)
    					{
    			 switch (z)
    						{
    			case 10: z='A'; s.push(z); m = m / 16; break; ////////////////////////////////////////////////////
    			case 11: z='B'; s.push(z); m = m / 16; break; // EMBEDDED SWITCH STATEMENT TO CONVERT		//
    			case 12: z='C'; s.push(z); m = m / 16; break; // FROM INTEGER TO CHAR VALUES FOR HEXADECIMAL    //
    			case 13: z='D'; s.push(z); m = m / 16; break; // OUTPUT						//
    			case 14: z='E'; s.push(z); m = m / 16; break; //						//
    			case 15: z='C'; s.push(z); m = m / 16; break; ////////////////////////////////////////////////////							
    						} 
    					}
    	}	
     
    	 while(!s.emptystack())
    		{
    		  
    		 p = s.pop();	
    		 if(p<9)                                        //LAST IF STATEMENT TO DETERMINE IF OUTPUT IS CHAR OR INT
    		 {
    		 cout<<(int)p;
    		 }
    		 else if(p>9)
    		 {
    		 cout<<(char)p;
    		 }
    
    		
    		}
    		cout<<"\nPRESS 'y' TO CONTINUE: ";
    	cin>>j;
    	while(j !='y')
    	{
    	cout<<"\nYou entered an invalid response:";
    	cout<<"\nPlease re-enter your choice: "; 
    	cin>>j;
    	}
    		break;
    
    	
    	case '4':
    	 
    		return 0;
    	
    	 break;
    	
    	
    	}
    	
    	
    }
    }
    this bit of code is a stack operation that I just put together no to long ago. It is used to convert decimal values to hexadecimal octal and binary values. It works like a charm. Be sure to trace the program line by line. The easiest way to trace this one is to examine one switch statement at a time.

  9. #9
    #include<xErath.h> xErath's Avatar
    Join Date
    Jun 2004
    Posts
    722
    In my homeland corrected identation is frequently used...
    DON'T mess spaces with tabs.. the result is awfull, and 3 4 empty consecutives lines have no point.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and pointer problem
    By ramaadhitia in forum C Programming
    Replies: 2
    Last Post: 09-11-2006, 11:41 PM
  2. infix evaluation using stack
    By lewissi in forum C++ Programming
    Replies: 0
    Last Post: 11-03-2005, 01:56 AM
  3. Question about a stack using array of pointers
    By Ricochet in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2003, 09:12 PM
  4. error trying to compile stack program
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-03-2003, 05:27 PM
  5. Stack Program Here
    By Troll_King in forum C Programming
    Replies: 7
    Last Post: 10-15-2001, 05:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21