Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...