#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node* next;
}node;
node* create(int data) {
node* newnode = malloc(sizeof(node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void insert(int data, node** head) {
node* newnode = create(data);
if (*head == NULL) {
*head = newnode;
}
else {
newnode->next = *head;
*head = newnode;
//只改了这里的两行代码
}
}
void show(node* head) {
while (1) {
printf("%d", head->data);
if (head->next == NULL) {
break;
}
head = head->next;
}
}
int main() {
int a = 1, b = 2, c = 3;
node* head = NULL;
insert(a, &head);
insert(b, &head);
insert(c, &head);
show(head);
return 0;
}
//PS:在主函数里面的head初始化为NULL就行了,别也动态分配内存,这样只分配了内存但没有初始化为NULL,insert函数不好找尾节点,而且在主函数对head进行动态分配没啥用,让他默认为空指针就行了
Comments NOTHING