[英]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.