C++用尾插法创建一个带头节点的单链表写出代码
时间: 2023-03-31 12:02:30 浏览: 128
好的,以下是用尾插法创建一个带头节点的单链表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createList() {
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
return head;
}
void insert(LinkedList head, int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
Node *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
int main() {
LinkedList list = createList();
insert(list, 1);
insert(list, 2);
insert(list, 3);
Node *p = list->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return ;
}
```
希望能够帮到您!
阅读全文