Re: basic C++ pointer stuff
When you push one item into stack, actually, you need to allocate a piece of memory and its size is struct nodeType. In your push(), you only decalre a nodePtrType, which is a pointer address not a entire struct of nodeType.
void stack::push(int& item)
{
nodePtrType *temp; // pointer
temp = new (struct nodeType); // allocate a new node from heap
temp->items = item;
temp->nextPtr = S;
S = temp;
}
After you pop out one item, you need to free the memory. There are one problem: if there are no more item in the stack, what are you gonna do?
/*************************************************************/
void stack::pop(int& item)
//pre: stack has at least one element
//post: top element is removed from stack
{
nodePtrType temp;
if(S == NULL){
cout << "No more item in stack!!\n";
return;
}
temp = S;
item = temp->items;
S = temp->nextPtr;
delete temp; // free memory
}
Also, you need to test the S before accessing it to avoid crashing.
int stack::topItem()
//pre: stack has at least one item
//post: top item of stack is returned
{
if(S == NULL){
cout <<"Stack is empty!!\n";
return 0;
}
item = S->items;
return item;
}
/////////////////////////////////////////////////////////////////
Hope this will help. Good luck.
Allen
Re: basic C++ pointer stuff
thanx. this was a great help. but one questions remains; how do code the class definition and its member functions to make it usable as a header file?
Re: basic C++ pointer stuff
File stack.h
=============
//stack- definition of linked list data structure
struct nodeType;
typedef nodeType* nodePtrType;
typedef int itemType;
struct nodeType
{
itemType items;
nodePtrType nextPtr;
};
//---------------Definition of class stack------------------
class stack {
public:
initStack(); //initializes stack
void listWrite(); //prints out entire stack
void push(int&); //puts an inputed integer on top of stack
void pop(int&); //removes top item from stack
int topItem(); //returns top item of stack
private:
nodePtrType S;
};
//end of header file
File stack.cpp
#include "stack.h"
and the rest of your source code changed as per Allen's specifications
sally
Re: basic C++ pointer stuff
I hope this is the correct answer, for the question you asked is incredibly simple...
All you have to do is put the class definition and member functions in a seperate file with the extension *.h, then just include that where you want to use the declarations