c++编写链表代码输入值
时间: 2023-05-19 10:02:53 浏览: 60
非常感谢您的提问!以下是一个简单的 C 语言链表代码示例:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int main() {
struct node *head = NULL;
struct node *current = NULL;
// 添加节点
for (int i = 1; i <= 5; i++) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = i;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
current = new_node;
} else {
current->next = new_node;
current = new_node;
}
}
// 遍历链表并输出
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
```
这段代码创建了一个简单的链表,包含了一个结构体 `node`,其中包含了一个整数 `data` 和一个指向下一个节点的指针 `next`。在 `main` 函数中,我们首先创建了一个空的链表头 `head` 和一个指向当前节点的指针 `current`。然后,我们使用一个循环来添加五个节点到链表中。每个节点都是通过动态内存分配来创建的,并且在添加到链表中后,我们更新了 `current` 指针,以便它指向最后一个节点。最后,我们遍历整个链表并输出每个节点的数据。
希望这个示例能够帮助您理解如何编写 C 语言的链表代码!