用C++写一个头插法链表
时间: 2023-03-30 17:04:56 浏览: 139
好的,我可以回答这个问题。以下是用 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*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct* 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("链表的元为: ");
printList(head);
return ;
}
```
这个程序会创建一个头指针 `head`,并使用 `insert` 函数来插入新的元。每次插入新元素时,都会将新元素插入到链表的头部。最后,使用 `printList` 函数来打印链表的所有元素。