直接贴上代码
#include <bits/stdc++.h>
using namespace std;
typedef struct Node {
int data;
Node *next;
} Node;
typedef struct Head {
Node *root;
} Head;
void Insert(Head *head, int value) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = value;
node->next = NULL;
if (head->root == NULL)
head->root = node;
else {
Node *temp = head->root;
while (temp != NULL) {
if (temp->next == NULL) {
temp->next = node;
return;
} else {
temp = temp->next;
}
}
}
}
void preorder(Node *node) {
while (node != NULL) {
cout << node->data;
node = node->next;
if (node != NULL)
cout << "-->";
}
}
int main() {
int arr[10] = {5, 2, 1, 4, 5, 3, 6, 2, 1, 4};
Head head;
head.root = NULL;
for (int i = 0; i < 10; i++) {
Insert(&head, arr[i]);
}
preorder(head.root);
cout << endl;
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/db07eaeaebbffbedff83c1e318f61264.png)