链表的插入问题~~
#include <stdio.h>#include <math.h>
#include <string.h>
#define LEN sizeof(struct lb)
struct lb
{
int c1;
int c2;
struct lb *next;
};
int n;
struct lb *tou(void)
{
struct lb *head,*p1,*p2;
n=0;
p1=(struct lb*)malloc(LEN);
p2=p1;
scanf("%d %d",&p1->c1,&p1->c2);
head=NULL;
while(p1->c1!=0)
{
n=n+1;
if(n==1)
head=p1;
else
{
p2=p1;
p1=(struct lb*)malloc(LEN);
fflush(stdin);
scanf("%d %d",&p1->c1,&p1->c2);
p2->next=p1;
}
}
p2->next=NULL;
return(head);
}
void main()
{
struct lb *cr(struct lb *head);
struct lb *sc(struct lb *head,int i);
struct lb *p,*head;
int i,k;
head=tou();
p=head;
while(p!=NULL)
{
printf("%d %d\n",p->c1,p->c2);
p=p->next;
}
p=head;
printf("n=%d\n",n-1);
printf("要删除学号请输入1\n");
printf("要添加学号请输入2\n");
printf("退出输入0\n");
fflush(stdin);
scanf("%d",&i);
if(i==1)
{
printf("请输入要删除的学号:\n");
fflush(stdin);
scanf("%d",&k);
head=sc(head,k);
}
else
if(i==2)
{
head=cr(head);
}
else
printf("谢谢使用\n");
p=head;
while(p!=NULL)
{
printf("%d %d\n",p->c1,p->c2);
p=p->next;
}
}
struct lb *sc(struct lb *head,int k)
{
struct lb *p1,*p2;
p1=head;
if(head==NULL)
{
printf("空表");
}
else
{
while((p1->c1!=k)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p1->c1==k)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
}
else
if(p1->next==NULL)
{
printf("找不到信息\n");
}
}
return(head);
}
struct lb *cr(struct lb *head)
{
struct lb *p0,*p1,*p2;
p1=head;
p2=p1;
p0=(struct lb*)malloc(LEN);
printf("请输入要添加的学号和成绩:\n");
scanf("%d %d",&p0->c1,&p0->c2);
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while((p1->c1)<(p0->c1)&&(p1->next!=NULL)) /*这个地方不明白,原来是用的逻辑运算符"||"可是不行p1->c1已经大于p0->c1了 可是程序还是在自加,用&&却正常。为什么?高手能给个解释吗?*/
{
p2=p1;
p1=p1->next;
}
if((p1->c1)>(p0->c1))
{
printf("c1=%d next=%o c1=%d\n",p1->c1,p1->next,p2->c1);
p2->next=p0;
p0->next=p1;
}
else
if(p1->c1==p0->c1)
{
printf("学号重复\n");
}
else
if(p1->next==NULL)
{
p1->next=p0;
p0->next=NULL;
}
}
return(head);
}