问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *creat(int a[],int n);
struct node *insert(struct node *head,int x);
void print(struct node *head);
int main()
{
struct node *head=NULL;
int a[10];
int repeat,i,j,n,x;//x-待插入的数据
scanf("%d",&repeat);
for(i=0;i<repeat;i++)
{
scanf("%d",&n);
for(j=0;j<n;j++)
scanf("%d",&a[j]);
scanf("%d",&x);
head=creat(a,n);
insert(head,x);
head=insert(head,x);
printf("size=%d:",n+1);
print(head);
printf("\n");
}
return 0;
}
struct node *creat(int a[],int n)
{
int i;
struct node *head=NULL,*end,*p;
end=head;
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->data=a[i];
p->next=NULL;
if(head==NULL)
{
head=p;
end=head;
}
else
{
end->next=p;
end=end->next;
}
}
end->next=NULL;
return head;
}
struct node *insert(struct node *head,int x)
{
struct node *p1=head,*p2=head->next,*p3=NULL,*end=NULL;
p3->data=x;
p3->next=NULL;
for(end=head;end->next!=NULL;end=end->next);//最后一个结点
if(p3->data<head->data)//插入点在头结点前
{
p3->next=head;
return p3;
}
else if(x>end->data)
{
end->next=p3;
return head;
}
else//插入点在链表中间
{
for(p1=head;p1!=NULL,p2!=end;p1=p1->next)
{
p2=p1->next;
if(x>=p1->data&&x<=p2->data)
{
p1->next=p3;
p3->next=p2;
}
}
return head;
}
}
void print(struct node *head)
{
struct node *p;
p=head;
for(p=head;p!=NULL;p=p->next)
{
if(p==head)
printf("%d",p->data);
else
printf(" %d",p->data);
}
}