struct Node {
int data;
struct Node* next;
};
void insertNode(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 = NULL;
struct Node* last = *head_ref;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
int i, n, data;
printf("请输入链表中节点的个数: ");
scanf("%d", &n);
printf("请输入链表中的元素: ");
for (i = 0; i < n; i++) {
scanf("%d", &data);
insertNode(&head, data);
}
printf("正序链表: ");
printList(head);
return 0;
}
暂无评论