-
Dynamic stack?
I have an assignment to do and I don't know what the term dynamic stack means. All I was given was the header and the rest is up to me.
Code:
class Stack
{
public:
Stack();
Stack(const Stack &stck);
~Stack();
void push(int number);
void pop();
int top() const;
bool isEmpty() const;
int size() const;
};
I also have no idea what top() is supposed to do. Read the value of the top of the stack?
Can someone write me some code how to make a stack of unknown size (I'm assuming that's what dynamic means)? I can write a "normal" stack but have no idea how to do a dynamic one.
-
I imagine your requirements are to write an implementation of a stack type that is unlimited in the amount of elements that it can hold (limited by hardware of course).
Are you allowed to use existing standard C++ classes? If so, look up the vector class. You may find it useful. If you are not allowed to do this, then I would suggest you make a linked list of sorts. A doubly-linked list would do fine. You can use an array, however, you have to resize it everytime you need more space than it has to offer.
top() is similar to pop(). It just means to return the element without actually removing it from the stack.
For more information on the structure itself:
http://en.wikipedia.org/wiki/Stack_(data_structure)
-
I don't quite follow you. Why would you need a doubly linked list for a stack? Shouldn't a singly linked list work?
-
It should, yes. It would be simpler to implement and would require less memory, too.
-
Just a quick question.
Why is this crashing at last printout?
Code:
struct node
{
int data;
node *next;
};
node *head;
void push(int data)
{
node* newnode = new node;
newnode->data = data;
newnode->next = head;
head = newnode;
}
void printout()
{
while(head != NULL)
{
node *save = head->next;
cout<< head->data <<' ';
delete head;
head = save;
}
-
Maybe because you never initialize head to null?
-