我想知道以下代码中p2的定义while (head->next != tail) { p1 = head; p2 = p1->next; while (p2 != tail) { if (p1->total < p2->total) { // swap nodes struct student *tmp = p1->next; p1->next = p2; p2 =
时间: 2023-04-08 12:03:31 浏览: 74
p2->next = tmp;
p1->next = tmp->next;
tmp->next = p2;
swapped = 1;
}
p1 = p2;
p2 = p2->next;
}
tail = p1;
if (!swapped) {
break;
}
head = head->next;
}
p2是一个指向结构体student的指针变量,它的定义在while循环的外部,它的作用是在while循环中用来交换节点。
相关问题
我想知道以下代码的问题while (head->next != tail) { p1 = head; p2 = p1->next; while (p2 != tail) { if (p1->total < p2->total) { // swap nodes struct student *tmp = p1->next; p1->next = p2; p2 =
这段代码的问题是可能会出现死循环,因为循环条件只判断了head->next是否等于tail,而没有判断head是否等于tail,如果head等于tail,就会一直循环下去。建议在while循环中加上head != tail的判断条件。
创建动态链表并打印链表内容。要求通过键盘读入学生的学号和分数,当输入的学号为0时表示链表创建结束,并将读入的学生学号和成绩打印输出。下面程序中存在比较隐蔽的错误,请通过分析和调试程序,发现并改正程序中的错误。改错时不能改变程序原有的意图。 注意:将修改后的完整的源程序写在答题区内。 #include <stdio.h> #define SIZE sizeof(struct node) struct node { long num; float score; struct node *next; } int main() { int n = 0; struct node *head = NULL, *p1, *p2; p1 = p2 = (struct node*)malloc(SIZE); printf("Input %d node data:\n", n + 1); scanf("%d%f", &p1->num, &p1->score); while (p1->num != 0) {
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student{
int num;
int grade;
struct student *next;
}STU;
int main(){
STU *head, *tail, *p;
head = (STU*)malloc(sizeof(STU));
head->next = NULL;
printf("please input the score (num grade):");
tail = head;
while(1){
p = (STU*)malloc(sizeof(STU));
scanf("%d", &p->num);
if(p->num == 0){
break;
}
scanf("%d", &p->grade);
tail->next = p; // 错误:没有将 p 链接到尾节点上,导致只有第一个节点被链接
tail = p;
}
printf("\nnum\tgrade\n");
p = head->next; // 错误:没有将 p 指向链表的第一个节点
while(p != NULL){
printf("%d\t%d\n", p->num, p->grade);
p = p->next;
}
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)