#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* next;//声明一个结构体
};
int main() {
struct node * head, * p, * q=NULL, * t;//不同含义的结点
int i, n, a;
scanf("%d", &n);
head = NULL;
for (i = 0; i < n; i++) {
scanf("%d", &a);
p = (struct node*)malloc(sizeof(struct node));//结构体指针(动态申请一个空间,用来存放一个结点,并用临时指针p只想这个结点)
p->data = a;
p->next = NULL;
if (head == NULL) {
head = p;
}
else
q->next = p;
q = p;
}
scanf("%d", &a);
t = head;//因为不能改变头结点所以要用一个临时变量t从头开始遍历
while (t != NULL) {
if (t->next->data > a) {
p = (struct node*)malloc(sizeof(struct node));
p->data= a;
p->next = t->next;//有值有指针
t->next = p;
break;
}
t = t->next;
}
t = head;//
while (t != NULL) {
printf("%d ", t->data);
t = t->next;
}
t = head;
while (t != NULL) {
p = t;
t = t->next;
free(p);
}
return 0;
}
ps:
1.
所以为了避免这个情况,我们要*q=NULL,
2.