Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Pointer is not modifying in insert in C

Program for priority queue, I have doubt in pointer, I am passing head to insert but its not modifying in insert, as you can see I am printing the head

  • in insert and main
  • in insert it is printing something non zero
  • and in head it is zero
    #include<stdio.h>
    #include<stdlib.h>
    struct node{
        int data;
        int priority;
        struct node* next;
    };
    struct node* getnewnode(int data,int priority){
        struct node* newnode=malloc(sizeof(struct node));
        newnode->data=data;
        newnode->next=NULL;
        newnode->priority=priority;
        return newnode;
    }
    void insert(struct node* head,int data,int priority){

        struct node* newnode=getnewnode(data,priority);
        if(head==NULL){
            head=newnode;
            printf("head in insert is %d",head);
            return;
        }

        if(head->priority > newnode->priority){
            newnode->next=head;
            head=newnode;
            return;
        }
        if(head->priority <= newnode->priority ){
            struct node* temp=head;
            while(temp->priority <= newnode->priority ){
                temp=temp->next;
            }
            newnode->next=temp->next;
            temp->next=newnode;
            return;
        }
    }
    int removee(struct node* head){
        if(head==NULL)
            return -1;
        int temp=head->data;
        head=head->next;
        return temp;
    }
    int main(){
        struct node* head=NULL;
        insert(head,3,5);
        printf("
 head in main is %d",head);

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Super-simplified version without any if() statements:


void insert(struct node **head, int data, int priority){

    struct node *newnode = getnewnode(data, priority);

    for( ; *head && (*head)->priority <= newnode->priority; head = &(*head)->next)
        {;}

    newnode->next = *head;
    *head = newnode;

    return;

}

... if you don't like empty loops, you could add a if(...) break;:


void insert(struct node **head, int data, int priority){

    struct node *newnode = getnewnode(data, priority);

    for( ; *head ; head = &(*head)->next) {
        if( (*head)->priority > newnode->priority) break;
        }

    newnode->next = *head;
    *head = newnode;

    return;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...