Stack and Queue Question Two

So I'm working on a little project. When you use a push method, you need to add the element to the top of the stack. If you're using a linked list, that would mean it would be the last element right?
Both the first and the last element could work. Just be consistent.

top - first element in the list
push - add element to the front of the list
pop - remove first element from the list

top - last element in the list
push - add element to the end of the list
pop - remove last element from the list
Okay. And lets say I wanted to return the node on top when I call the top method.... Could I use the function type "node"?


i.e.


node
LinkedStack::Top()
{
	node * current = head;
	node * tail = current;
	while(current != NULL)
	{
		tail = current; 
		current = current->next;
	}
	return *tail;
}


The reason I ask is because it works with the Visual Studio compiler and I wanted to make sure its not bad practice or anything that would be frowned upon.
Last edited on
Returning the list node (i.e. using a return type of node) exposes the inner workings of your stack. You should consider retuning just the data associated with the node.

Andy

PS I would also consider working with the head of the list as the "top". As Peter87 said, you can use either the head or the tail of the list to implement push, pop, top. But if you use the tail, you have to walk the list a lot more often, unless you keep track of the last as well as the first element of the list.
Last edited on
So if it says "return the top element on the stack", its referring to the data, not necessarily the data AND the pointer?
top - first element in the list
push - add element to the front of the list
pop - remove first element from the list


When you say "push - add element to the front of the list" when I'm referring to stack ADT, would that mean it would go to the very first element in the list? Or would the front be the last element?
#1 The elements are what's on the stack (the data). Not the list nodes used to store the data.

#2 "push - add element to the front of the list" means that you make "head" point to the new elem, at the front of the list, and then hook it up to point to the pre-exisiting elements.
So if I were to add these numbers in sequential order, like so:

1, 2, 3, 4, 5, 6, 7, 8, 9

The order that the push method should be placing them in would be:

9, 8, 7, 6, 5, 4, 3, 2, 1

Would that be true?
Yes

(if the head/front of your list is the top of your stack)
Last edited on
Topic archived. No new replies allowed.