I have an assignment that is asking me to fill up a stack with random variables and pop them out in a FILO order. Whilst I managed to get it to fill the stack, it seems to be popping out the last element and nothing else. I'm not sure why. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define STACK_SIZE 10
#define STACK_EMPTY -1
void push(char [], // input/ouput - the stack
char, // input - data being pushed onto the stack
int *, // input/output - pointer to the index of the top of stack
int); // constant - maximum size of stack
char // output - data being popped out from the stack
pop(char [], // input/output - the stack
int *); // input/output - pointer to the index of the top of stack
void push(char stack[],char item,int *top,int max_size){
stack[*top++] =item;
}
char pop(char stack[],int *top){
return stack[*top--];
}
int main(){
char s[STACK_SIZE];
int s_top = STACK_EMPTY; // Pointer points to the index of the top of the stack
char randChar = ' ';
int i = 0;
int j=0;
int randNum = 0;
srand(time(NULL));
for (i = 0; i < STACK_SIZE; i++){
randNum = 33 + (int)(rand() % ((126-33)+ 1 ));
randChar = (char) randNum;
push(s,randChar, &s_top, STACK_SIZE);
printf ("Random char: %c\n", randChar);
}
printf("-----------\n");
for(j=STACK_SIZE; j>0; j--){
printf("Random chars:%c\n", pop(s, &s_top));
}
return 0;
}
Whenever we push (add) elements into the stack then increment the counter that indicates the size of the stack has increased now and whenever we pop (remove) elements from the stack then decrement the counter that indicates decrement in size of the stack.
Push: This function adds an element to the top of the Stack. Pop: This function removes the topmost element from the stack. IsEmpty: Checks whether the stack is empty. IsFull: Checks whether the stack is full.
C++ Stack pop() function is used for removing the topmost element of the stack. This function performs the deletion operation. Deletion in a stack is done from the top. The element which was most recently inserted is deleted first.
Time Complexity: O(1), In the push function a single element is inserted at the last position. This takes a single memory allocation operation which is done in constant time.
Your push should be
(*top)++;
stack[*top] = value;
That is first increment to the next empty position and then insert. The top
variable always points to the top element. Therefore to push, first increment then assign. To pop, first extract the value at top and then decrement.
Note: the above line can be clubbed to stack[++(*top)] = value
In the current code, at the first push, your code with stack[*top++] = item
, with the post increment attempts to assign the value to the current value of *top
which is -1
and then increment, which is wrong.
With respect to this modification of push routine the pop routine is okay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With