题目:把k的值插入到b前面,b是程序里面的数,程序里没有b,k插入到最后。
问题: 如果b是程序里第一个数,要求插入到第一个数前面,但是老是插到最后,求改正,其他插入没错。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct student
{
int data;
struct student *next;
}a;
struct student *p,*q,*head,*l,*m,*t;
int main()
{
l=q=head=&a;
int n,i,c=0,k,b;
printf("请输入n:\n");
scanf("%d",&n);
q->next=NULL;
printf("输入链表:\n");
for(i=0;i<n;i++)
{
p = (struct student*)malloc(sizeof(struct student));
c++;
if(c==1) t = head = l = p;
scanf("%d",&p->data);
q->next = p;
q = q->next;
}
p->next=NULL;
printf("请输入b,k的值:\n");
scanf("%d%d",&b,&k);
m = (struct student*)malloc(sizeof(struct student));
m->data = k;
c=0;
printf("把值插入链表中为:\n");
l = head->next;
q = &a;
for(i=0;i<n;i++)
{
c++;
if(l->data == b&&c==1)
{
q->data = k;
break;
}
else if(l->data == b)
{
head->next = m;
m->next = l;
break;
}
if(c==n-1)
{
p->next = m;
m->next=NULL;
}
l = l->next;
head = head->next;
}
for(i=0;i<n+2;i++)
{
printf("%d\n",t->data);
t = t->next;
}
return 0;
}