[英]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;
}
您需要將指針頭的地址傳遞給函數push。 我的情況是頭部沒有被修改,因為你只是在頭部傳遞值。
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;}
您正在按值將head
指針傳遞給函數push(head,temp);
. 在push
內完成的head
更改不會反映在main()
函數中。
您應該將head
地址傳遞給push()
。
push(&head, temp);
和內部push()
:
*head = n;
pop()
也需要類似的更改。 您可以通過在main()
的循環中添加一個printf
來驗證我在說什么: printf("%p\\n", head);
. head
的值將保持不變。
順便說一句,在printf
內的語句末尾添加一個\\n
是一種很好的做法,它會立即刷新stdout
流,因此您的輸出會立即打印在stdout
(您的計算機屏幕)上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.