Hey Guys I am making a C++ Stack program for a school assignment and I have a quick question. I just learned about stacks so bear with me.... how do you print the contents of the stack?? also is it going to print it backwards? If so how would I go about printing it forwards??
I think I have an idea of what I need to do and it would involve nodes and pointers but can you give me some help?
Thanks!
C++ Stack Question?
Stack is known as a Last In, First Out object.
Only the last item pushed onto the stack is accessible.
typedef struct list_node
{
int data;
struct list_node *next;
} *list_node_ptr;
class Stack
{
list_node_ptr head, current;
list_node_ptr MakeNode(int data)
{
return new list_node(data, NULL);
}
public:
Stack() {head = current = NULL;}
void Push(int value)
{
list_node_ptr link = MakeNode(value, NULL);
if (head == NULL)
head = current = link;
else
{
current-%26gt;next = link;
current = link;
}
}
int Pop()
{
if (head == NULL)
{
throw "Stack Empty"; // remove this if not use exceptions
return 0;
}
else
{
int v = Examine();
if (head == current)
{
delete head;
head = current = NULL;
}
else
{
for (list_node_ptr link = head; link-%26gt;next != current; link = link-%26gt;next);
delete current;
current = link;
current-%26gt;next = NULL;
}
return v;
}
int Examine() {return (current ? current-%26gt;data : 0);}
}
Reply:You can print it either forwards or backwards, it's up to you. A stack is usually stored backwards, that is, the most recent data is at the bottom and oldest data is at the top.
When you say you are making a C++ Stack program, does that mean you are implementing your own stack data structure? It's hard to answer your question without knowing exactly what kind of stack you are talking about.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment