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 函数创建一个临时结构元素并存储函数参数中给出的数据。那么 temp 的 next 指针指向链表的根指针。
Pop 函数创建一个指向根指针的临时结构元素。然后根指针在输入的下一个最后一个元素上迭代。并且临时元素被删除。
尝试让 pop 函数返回堆栈中最后输入的元素,并在每次调用后将其删除,但第二次失败。 因为在 pop 函数中 s* (根指针)不会被迭代。我该如何解决这个问题? 谢谢你。
通过引用而不是值传递节点,例如:
int pop(node** s) {
if (*s == NULL) {
printf("Stack is empty\n");
return -1;
}
node* temp = *s;
int rvalue = temp->data;
*s = (*s)->next;
free(temp);
return rvalue;
}
流行音乐的呼唤就像是
printf("%d\n", pop(&root));