为什么循环时我的链表不起作用?(C)
我不确定为什么下面的代码不执行while循环。它只提供以下输出: 该程序的理想输出是取链表的最大节点,乘以0.8,然后打印为输出为什么循环时我的链表不起作用?(C),c,linked-list,C,Linked List,我不确定为什么下面的代码不执行while循环。它只提供以下输出: 该程序的理想输出是取链表的最大节点,乘以0.8,然后打印为输出 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 p
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);
代码:
结构过程{
int突发时间;
结构进程*下一步;
};
int main()
{
int i;
结构进程*head=NULL,*temp=NULL;
struct Process*current=head;//重置指针
整数进程计数、时间量、总时间;
//BTmax
int max=0;
printf(“有多少个进程?”:”;
scanf(“%d”,&proc\u计数);
对于(i=0;iburst\u time);
temp->next=NULL;
if(head==NULL)
{
压头=温度;
电流=水头;
}
其他的
{
当前->下一步=温度;
电流=温度;
}
}
电流=水头;
//BTmax*0.8
while(当前!=NULL)
{
如果(头部->爆破时间>最大值)
{
最大值=水头->爆破时间;
}
头部=头部->下一步;
}
时间_量子=最大值*0.8;
printf(“\n时间量为:%d”,时间量);
此外,在while循环中,您正在迭代head变量,但在条件下,您正在检查current!=NULL您将要更改最终while循环。您正在检查以确保当前while循环不是NULL
但您正在使用head
进行迭代。如果您仍然需要访问数据,请更改最终while循环面向对象的方法应该可以:
while(current != NULL) {
if (current->burst_time > max) max = current->burst_time;
current = current->next;
}
最后,可能您的实际程序中已经有了,但是您需要free()
使用malloc()分配的任何内存
因此,如果此时已完成列表,则可以将最终while循环更改为:
while(head != NULL) {
if (head->burst_time > max) max = head->burst_time;
temp = head;
head = head->next;
free(temp);
}
从您编写循环(通过head=head->next
进行迭代)时的方式来看,您显然试图同时完成这两件事:
- 扫描列表中最大的元素
- 在考虑每个元素后删除/取消分配它
虽然head=head->next
确实从列表中删除了每个元素,但它忽略了释放(导致内存泄漏)
此循环正确执行扫描和删除/解除分配:
while (head != NULL)
{
if (head->burst_time > max)
{
max = head->burst_time;
}
temp = head;
head = head->next;
free(temp);
}
(请注意,while
条件应该是测试head
,而不是测试current
。因此,无需在循环之前初始化current=head
。)风格指南:点
和箭头->
操作符绑定得很紧,因为它们是。它们不应该用空格来写。写&temp->burst\u time
不是惯用的C,表明编码者是一个新手。使用&temp->burst\u time
。还有人觉得程序输出奇怪吗?它不应该只是在while循环中旋转,因为电流永远不会为NULL吗?是atexit()或类似文件的“进程返回…”位的一部分吗?还是从辅助程序输出的?这非常有用。谢谢!