struct n {
int data;
struct n* next;
};
typedef struct n node;
node* push(node* s, int x) {
node* temp;// temporary element
temp = (node*)malloc(sizeof(node));
if (temp == NULL) {
printf("not enough memory.");
return -1;
}
// creates a new element that stores the data and pointed by the root pointer
temp->data = x;
temp->next = s;
s = temp;
return s;
}
int pop(node* s) {
if (s == NULL) {
printf("Stack is empty\n");
return -1;
}
// create a temporary elements points the root pointer.
// after iteration temporary elements will be deleted.
node* temp = (node*)malloc(sizeof(node));
temp = s;
int rvalue = temp->data;
s = s->next;
free(temp);
return rvalue;
}
int main() {
node* root = NULL;
root = push(root, 10);
root = push(root, 20);
root = push(root, 30);
printf("%d\n", pop(root));
printf("%d\n", pop(root));
return 0;
}
Push function creates a temporary struct element and stores the data that given in the function parameter. then temp's next pointer points the root pointer for linking list.
Pop function creates a temporary struct element that points the root pointer. then root pointer is iterated next last element that entered. And temporary element is deleted.
Trying to make the pop function returns the last entered elements of stack and remove it after every call, but it fails in the second. Beacuse in the pop function s* (root pointer) will be not iterated. How can I fix that? Thank you.
pass the node by reference not by value, for example:
The call of pop would be like