[英]What's with the program why is it not printing any result?
struct node{
int data; struct node *next;
};
void push(struct node* head, struct node* n){
if(n!= NULL){
if(head==NULL)
head = n;
else {
n->next = head;
head = n;
}
} else printf("Cannot insert a NULL node");
}
struct node* pop(struct node* head){
if(head!=NULL){
struct node *n = head;
head = head->next;
return n;
} else {
printf("The stack is empty");
return NULL;
}
}
int main(){
int i;
struct node *head = NULL, *n;
for(i=15;i>0;i--){
struct node *temp = malloc(sizeof(struct node));
temp -> data = i;
temp->next = NULL;
push(head,temp);
}
n = head;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
return 0;
}
You need to pass the address of the pointer head to the function push.您需要将指针头的地址传递给函数push。 I your case the head is not getting modified because you are only passing the value in the head.
我的情况是头部没有被修改,因为你只是在头部传递值。
void push(struct node** head, struct node* n){
if(n!= NULL){
if(*head==NULL)
*head = n;
else {
n->next = *head;
*head = n;
}
} else printf("Cannot insert a NULL node");}
int main(){
int i;
struct node *head = NULL, *n;
for(i=15;i>0;i--){
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp -> data = i;
temp->next = NULL;
push(&head,temp);
}
n = head;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
return 0;}
You are passing the head
pointer by value to the function push(head,temp);
您正在按值将
head
指针传递给函数push(head,temp);
. . The changes to
head
done inside push
will not be reflected in the main()
function.在
push
内完成的head
更改不会反映在main()
函数中。
You should pass address of head
to push()
.您应该将
head
地址传递给push()
。
push(&head, temp);
and inside push()
:和内部
push()
:
*head = n;
Similar change will be required for pop()
. pop()
也需要类似的更改。 You can verify what I am saying by adding a printf
inside the loop in main()
as: printf("%p\\n", head);
您可以通过在
main()
的循环中添加一个printf
来验证我在说什么: printf("%p\\n", head);
. . The value of
head
will remain unchanged. head
的值将保持不变。
BTW, it is good practice to add a \\n
at the end of statement inside printf
, it flushes the stdout
stream immmediately hence your output is printed immediately on stdout
(your computer screen).顺便说一句,在
printf
内的语句末尾添加一个\\n
是一种很好的做法,它会立即刷新stdout
流,因此您的输出会立即打印在stdout
(您的计算机屏幕)上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.