简体   繁体   中英

Why is my linked list while loop not working? (C)

I am unsure why the code below does not execute up to the while loop. It only gives this output: enter image description here

The desired output of this program is that the largest node of the linked list is taken, multiplied by 0.8, and then printed as an output.

Code:
struct Process{
int burst_time;
struct Process* next;
};

int main()
{
int i;
struct Process* head = NULL, *temp = NULL;
struct Process* current = head; // Reset the pointer
int proc_count, time_quantum, total_time;
// BTmax
int max = 0;
printf("How many processes?: ");
scanf("%d",&proc_count);
for(i = 0; i < proc_count; i++)
{
    temp = malloc(sizeof(struct Process));
    printf("\nEnter burst time of process %d: ", i + 1);
    scanf("%d", &temp -> burst_time);
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
        current=head;
    }
    else
    {
        current->next=temp;
        current=temp;
    }
}
current = head;
// BTmax * 0.8
while(current != NULL)
{
    if (head -> burst_time > max)
    {
        max = head->burst_time;
    }
    head = head->next;
}
time_quantum = max * 0.8;
printf("\nTime Quantum is: %d", time_quantum);

Also, inside while loop you are iterating head variable but in condition you are checking current != NULL

From the way you wrote your while loop (iterating via head=head->next ) you are apparently trying to do these two things at the same time:

  • Scan the list for its largest element
  • Remove/deallocate each element after it has been considered

Although head=head->next does remove each element from the list, it neglects to deallocate (causing memory to leak).

This loop correctly does both the scanning and the removal/deallocation:

while (head != NULL)
{
    if (head->burst_time > max)
    {
        max = head->burst_time;
    }
    temp = head;
    head = head->next;
    free(temp);
}

(Notice that the while condition should be testing head , not testing current . Thus, there is no need to initialize current=head prior to the loop.)

You'll want to change the final while loop. You're checking to make sure current isnt NULL but you're iterating with head . If you still need access to the data, changing the final while loop to this should work:

while(current != NULL)  {
    if (current->burst_time > max) max = current->burst_time;
    current = current->next;
}

Finally, maybe you already have in your actual program, but you need to free() any memory allocated with malloc() So if you're done with the list at that point you can change the final while loop to:

while(head != NULL) {
    if (head->burst_time > max) max = head->burst_time;
    temp = head;
    head = head->next;
    free(temp);
}

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