-
Stack manipulation
I am an advanced beginner c I am given a stack/push/pop assignement to do but I have no clue on how to do it. The book that I have sucks in explaining stacks and old threads in here are too complicated or advanced for me right now.
I am given this outline to go by:
Code:
for(;;)
{
fgets(command,sizeof(command), stdin);
if(feof(stdin))break;
if(command[0]=='p') push atoi (command+1) onto stack
if(command[0]=='w') pop number from stack
display contents of the stack
}
So I I want to ad 5678 to a stack I have to be able to write at the command: p 5678 or w 5678 to remove it from the stack
Please need help!!
-
>I am an advanced beginner
Ehm, ok.
A stack is a piece of memory which works according to the LIFO principe, data which is stored last will be retrieved first. There are two basic functions on stacks, push and pop. Push pushes data onto the stack and pop gets data from the stack.
Example:
An empty stack:
stack = []
Put data on stack
push (stack, 1)
The stack is now:
stack = [1]
Put more data on stack
push (stack, 2)
The stack is now:
stack = [1, 2]
Get data from stack
value = pop (stack)
Now:
value = 2
stack = [1]
So you could for example declare an array of size N and define push and pop functions onto it.
You could implement it something like this pseudo-code. But note that in this pseudo-code there is not taken care of the maximum size of the stack.
Code:
int stack [N]
function push (stack, variable)
begin
top = top + 1
stack [top] = variable
end
function pop (stack)
begin
value = stack [top]
top = top - 1
return value
end