C语言链表输入元素输出对应的值
时间: 2024-05-13 16:14:54 浏览: 16
这里是一个简单的示例代码,可以实现用链表输入元素并输出对应的值:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = newNode;
}
}
void printList(Node* head) {
Node* currentNode = head;
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
}
int main() {
Node* head = NULL;
int n, data;
printf("输入元素个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("输入第%d个元素的值:", i + 1);
scanf("%d", &data);
insert(&head, data);
}
printf("链表元素为:");
printList(head);
return 0;
}
```
在这个示例代码中,我们定义了一个 `Node` 结构体作为链表的节点,包含了一个 `data` 属性表示节点的值,以及一个 `next` 属性指向下一个节点。然后我们定义了 `insert` 函数用于在链表尾部插入节点,以及 `printList` 函数用于输出链表的元素。
在 `main` 函数中,我们首先输入元素的个数 `n`,然后遍历 `n` 次,每次输入一个元素的值并插入到链表中。最后输出链表的元素。
相关推荐
![](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)