簡體   English   中英

為什么我的鏈表 while 循環不起作用? (C)

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

我不確定為什么下面的代碼沒有執行到 while 循環。 它只給出了這個 output:在此處輸入圖像描述

這個程序想要的output就是取鏈表的最大節點,乘以0.8,然后打印為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);

此外,在 while 循環內,您正在迭代 head 變量,但在條件下您正在檢查當前!= NULL

從您編寫while循環的方式(通過head=head->next迭代),您顯然是在嘗試同時做這兩件事:

  • 掃描列表中的最大元素
  • 考慮后刪除/取消分配每個元素

盡管head=head->next確實從列表中刪除了每個元素,但它忽略了釋放(導致 memory 泄漏)。

此循環正確執行掃描和刪除/解除分配:

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

(注意while條件應該是測試head ,而不是測試current 。因此,沒有必要在循環之前初始化current=head 。)

您需要更改最后的 while 循環。 您正在檢查以確保current不是NULL但您正在使用head進行迭代。 如果您仍然需要訪問數據,將最終的 while 循環更改為此應該可以:

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

最后,也許你已經在你的實際程序中,但是你需要free()任何用malloc()分配的 memory 所以如果你已經完成了這個列表,你可以將最后的 while 循環更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM