求改错:单向链表的多次插入

pta题目段错误 太搞人心态了 看不出来哪里错了

1 #include<stdio.h>
2
struct node{
3
int data;
4
struct node *next;
5
};
6
struct node *create(int n){
7
struct node *head,*tail,p;
8
head=(struct node
)malloc(sizeof(struct node));
9
head->next=NULL;
10
tail=head;
11
for(int i=0;i<n;i++){
12
p=(struct node*)malloc(sizeof(struct node));
13
scanf("%d",p->data);
14
p->next=NULL;
15
tail->next=p;
16
tail=p;
17
}
18
return head;
19
}
20
struct node *insert(struct node *L,int x){
21
struct node *head,*p,temp;
22
head=L;
23
temp=(struct node
)malloc(sizeof(struct node));
24
temp->data=x;
25
temp->next=NULL;
26
while(L->next!=NULL&&L->next->data<=x){
27
L=L->next;
28
}
29
temp->next=L->next;
30
L->next=temp;
31
return head;
32
}
33
int main(){
34
int repeat;
35
scanf("%d",&repeat);
36
for(int i=0;i<repeat;i++){
37
struct node *head1,*head2,*p;
38
int n;
39
scanf("%d",&n);
40
head1=create(n);
41
int x;
42
scanf("%d",&x);
43
head2=insert(head1,x);
44
printf("size=%d:",n+1);
45
for(p=head2->next;p!=NULL;p=p->next){
46
printf("%d ",p->data);
47
}
48
printf("\n");
49
}
50
return 0;
51

img

img

!题目在此

img

修改如下,供参考:

#include <stdio.h>
#include <stdlib.h>
struct node {
        int data;
        struct node* next;
};
struct node* create(int n) {
    struct node* head, * tail, * p;
    head = (struct node*)malloc(sizeof(struct node));
    head->next = NULL;
    tail = head;
    for (int i = 0; i < n; i++) {
        p = (struct node*)malloc(sizeof(struct node));
        scanf("%d", &p->data);  //scanf("%d", p->data);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    return head;
}
//struct node* insert(struct node* L, int x)
void insert(struct node* L, int x) {
    struct node * p, * temp;   
    p = L;
    while (p->next != NULL && p->next->data < x) {
        p = p->next;
    }
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;
    temp->next = p->next;
    p->next = temp;
}
void print(struct node* L)
{
    struct node* p = L;
    while (p->next) {
        printf(p == L ? "%d" : " %d", p->next->data);
        p = p->next;
    }
    printf("\n");
}
void destroy(struct node* L)
{
    struct node* p = NULL;
    while (L) {
        p = L;
        L = L->next;
        free(p);
    }
    L = NULL;
}
int main() {
    int repeat, n, x;
    struct node* head1;
    scanf("%d", &repeat);
    for (int i = 0; i < repeat; i++) {
        scanf("%d", &n);
        head1 = create(n);
        scanf("%d", &x);
        insert(head1, x);
        printf("size=%d:", n + 1);
        print(head1);
        destroy(head1);
    }
    return 0;
}

贴的代码,放到代码段里面,额,不然不好看