使用链表对堆栈的推送操作失败 [英] push operation on stack using linked list fails
本文介绍了使用链表对堆栈的推送操作失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用单链表创建堆栈,我的推送操作没有将数据插入链表
I am trying to create a stack using single linked list, my push operation doesn't insert data into the linked list
这是我迄今为止尝试过的,
This is what I have tried so far,
typedef struct element {
int data;
struct element *next;
}node;
推送方式
void push(node *root, int data) {
if(root == NULL) {
root = (node *) malloc (sizeof(struct element));
root->data = data;
root->next = NULL;
}
else {
node *temp = (node *) malloc (sizeof(struct element));
temp->data = data;
temp->next = root;
root = temp;
}
}
在我的主方法中,我没有malloc
处理头指针,这就是我调用 push 方法的方式,
In my main method, I haven't malloc
ed the head pointer,
and this is how I call the push method,
push(head, data);
如何让推送操作生效?
推荐答案
push
函数中修改了 root
指针.此值不会传播到 main
.一种方法是返回 root
指针.
The root
pointer is modified in the push
function. This value is not propagated to main
. One way to do it is to return the root
pointer.
node* push(node *root, int data) {
if(root == NULL) {
root = (node *) malloc (sizeof(struct element));
root->data = data;
root->next = NULL;
}
else {
node *temp = (node *) malloc (sizeof(struct element));
temp->data = data;
temp->next = root;
root = temp;
}
return root;
}
在 main 中,你需要这样称呼它,
And in main, you need to call it like,
head = push(head, data);
这篇关于使用链表对堆栈的推送操作失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文