代码中很多细节都没有考虑,节点的释放,边界值问题,只是单纯的为了练手。
#include
#include
#define LEN sizeof(struct student)
struct student{//结构体定义
int a ;
struct student* next;
};
struct student * Create()//创建链表
{
struct student *head;
struct student *p1;
struct student *p2;
head=NULL;
p1=(struct student*)malloc(LEN);
p2=(struct student*)malloc(LEN);
printf("请输入信息");
scanf("%d",&p1->a);
while(p1->a!=0)
{
//p1->next=P2;
if(head==NULL)
head=p1;
else
{
p2->next=p1;
//p2=p1;
}
p2=p1;
p1=(struct student*)malloc(LEN);
printf("请输入信息");
scanf("%d",&p1->a);
}
p2->next=NULL;
return head;
}
void Print(struct student *head)//链表的输出
{
//printf("ok");
struct student*p1;
p1=head;
while(p1)
{
printf("%d",p1->a);
p1=p1->next;
}
printf("\n");
}
struct student * add( struct student*head,int x)//添加节点
{
struct student *p1;
struct student *p2;
struct student *p3;
p1=head;
while(p1->a<x)
{
p2=p1;
p1=p1->next;
}
p3=(struct student *)malloc(LEN);
p2->next=p3;
p3->a=x;
p3->next=p1;
return head;
}
struct student * dele( struct student *head,int x)//删除节点
{
struct student * p1;
struct student *p2;
p1=head;
while(p1->a!=x)
{
p2=p1;
p1=p1->next;
}
p2->next=p2->next->next;
return head;
}
int main()
{
struct student* start;
start=Create();
printf("创建的链表是:");
Print(start);
add(start,4);
printf("添加节点后的链表是:");
Print(start);
dele(start,2);
printf("删除节点后的链表是:");
Print(start);
return 0;
}