建立一个链表,依次输出几个结点的值
时间: 2023-06-04 17:02:46 浏览: 69
好的,这个问题是关于编程的,我可以帮您回答。下面是一个简单的链表的结构体定义和输出函数的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void print_list(struct node *head, int num_nodes) {
int i;
struct node *current;
current = head;
for (i = 0; i < num_nodes; i++) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct node *head, *current;
int num_nodes, i;
printf("Enter the number of nodes: ");
scanf("%d", &num_nodes);
head = NULL;
for (i = 0; i < num_nodes; i++) {
current = (struct node *) malloc(sizeof(struct node));
printf("Enter the value of node %d: ", i+1);
scanf("%d", ¤t->data);
current->next = head;
head = current;
}
printf("The values of the nodes are: ");
print_list(head, num_nodes);
return 0;
}
```
这个代码定义了一个结构体 `node`,它包含一个 `data` 属性和一个指向下一个结点的指针 `next`,主函数中先读入链表的结点个数,然后循环读入每个结点的值并创建链表。最后调用 `print_list` 函数输出链表的所有结点的值。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)