你可以用C++写一个链表吗
时间: 2023-05-12 11:04:48 浏览: 63
当然可以,链表是C语言中常用的数据结构之一,可以用指针来实现。以下是一个简单的链表实现示例:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
printf("Linked list: ");
printList(head);
return 0;
}
```
这段代码实现了一个简单的链表,可以插入新的节点并打印整个链表。