用指针创建一个具有三名同学学号和姓名的静态链表,数据自拟赋值最后用结构体指针将数据打印出来
时间: 2023-04-03 13:03:23 浏览: 74
好的,我可以回答这个问题。以下是代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
typedef struct student {
int id;
char name[MAX_NAME_LEN];
struct student *next;
} Student;
int main() {
Student *head, *p, *q;
int i;
// 创建链表
head = (Student *)malloc(sizeof(Student));
head->next = NULL;
q = head;
for (i = 0; i < 3; i++) {
p = (Student *)malloc(sizeof(Student));
p->id = i + 1;
sprintf(p->name, "Student%d", i + 1);
p->next = NULL;
q->next = p;
q = p;
}
// 打印链表
p = head->next;
while (p != NULL) {
printf("id: %d, name: %s\n", p->id, p->name);
p = p->next;
}
// 释放链表内存
p = head;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
return 0;
}
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)