简体   繁体   中英

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. 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); . The changes to head done inside push will not be reflected in the main() function.

You should pass address of head to push() .

push(&head, temp);

and inside push() :

*head = n;

Similar change will be required for pop() . You can verify what I am saying by adding a printf inside the loop in main() as: printf("%p\\n", head); . The value of head will remain unchanged.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM