建立一个链表每个结点包括的成员为:职工号、工资。用malloc打印出来。用一个creat 来建立链表,用list来输出数据。5个职工号为101,103,105,107,109。
时间: 2023-06-09 19:07:15 浏览: 56
好的,我来给您解答。
这是一个典型的链表操作问题,下面是完整代码实现:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int num;
float salary;
struct Node *next;
} Node;
// 创建链表
Node *creat() {
Node *head, *tail, *p;
int i;
head = (Node *)malloc(sizeof(Node));
tail = head;
for (i=1; i<=5; i++) {
p = (Node *)malloc(sizeof(Node));
p->num = 100 + i * 2 - 1;
p->salary = 2000 + i * 1000;
tail->next = p;
tail = p;
}
tail->next = NULL;
return head;
}
// 输出链表
void list(Node *head) {
Node *p;
p = head->next;
while (p != NULL) {
printf("职工号:%d,工资:%.2f\n", p->num, p->salary);
p = p->next;
}
}
int main() {
Node *head;
head = creat();
list(head);
return 0;
}
```
在上面的代码中,我首先定义了一个链表结构体,包括职工号和工资两个成员变量,还有一个指向下一个节点的指针。接着,在creat函数中,我使用malloc函数动态分配节点内存,然后利用for循环给节点赋值后,将新节点插入链表末尾。最后,将头结点返回。
在list函数中,我使用指针p遍历链表,将链表中所有节点的职工号和工资输出。
在main函数中,我调用creat函数创建链表,并将链表头指针传递给list函数进行遍历输出。
注意,代码中使用了动态内存分配的方式,所以在程序结束时记得释放所有申请的内存,避免内存泄漏。
希望我的回答能够帮到您!