简单的链表操做

#include<stdio.h>
#include<malloc.h>       //动态分配函数
struct cla{                              //定义结构体
 int num;
 char str[100];
 struct cla *next;
};
//------------------------建立链表函数-----------------------------------
struct cla *creat(void)
{
 struct cla *head,*p1,*p2;
 int n=0;
 head=NULL;
 p1=p2=(struct cla *)malloc(sizeof(struct cla));
 scanf("%d %s",&p1->num,p1->str);
 while(p1->num!=0)
 {
  n++;
  if(n==1)
   head=p1;
  else
   p2->next=p1;
  p2=p1;
 p1=(struct cla *)malloc(sizeof(struct cla));
 scanf("%d %s",&p1->num,p1->str);
 }
 p2->next=NULL;
 return head;
}
//--------------------------打印链表函数------------------------------------
struct cla *print(struct cla *head)
{
 struct cla *p;
 p=head;
 if(head==NULL)
 {
  printf("这是空链表\n");
  goto end;
 }
 else
  do{
   printf("%d %s ",p->num,p->str);
   p=p->next;
  }while(p!=NULL);
end:
  return head;
}
//-------------------------------删除结点函数------------------------------------
struct cla *del(struct cla *head,int shu)
{
 struct cla *p1,*p2;
 p1=head;
 if(head==NULL)
 {
   printf("这是空链表\n");
  goto end;
 }
 while(shu!=p1->num&&p1->next!=NULL)
 {
  p2=p1;
  p1=p1->next;
 }
 if(shu==p1->num)
 {
  if(head==p1)
   head=p1->next;
  else
   p2->next=p1->next;
   printf("删除的数是:%d\n",shu);
 }
 else
  printf("没有找到要删除的数\n");
end:
 return head;
}
//-----------------------------------------插入结点函数-------------------------------------------
struct cla *insert(struct cla *head ,struct cla *cha)
{
 struct cla *p,*p1,*p2;
 p=cha;
 p1=head;
 if(head==NULL){
  head=p;
  p->next=NULL;}
 else
    {
  while(p->num>p1->num&&p1->next!=NULL)
  {
   p2=p1;
   p1=p1->next;
  }
  if(p->num==p1->num)
  {
   if(head==p1)
    head=p;
   else
   // p1=p1->next;
   p2->next=p;
   p->next=p1;
  }
  else
  {
   p1->next=p;
   p->next=NULL;
  }
 }
  return head;
}
//------------------------------------主函数--------------------------------
void main()
{
 struct cla *head,*sb;
 int num;
 printf("请输入数据:");
 head=creat();
 printf("输出链表:");
 print(head);
 printf("\n输入要删除的数:");
  scanf("%d",&num);
 while(num!=0)
 {
  head=del(head,num);
  print(head);
 printf("\n输入要删除的数:");
  scanf("%d",&num);
 }
 sb=(struct cla *)malloc(sizeof(struct cla));
 printf("\n输入要插入的数和名字:");
 scanf("%d %s",&sb->num,sb->str);
 while(sb->num!=0)
 {
  head=insert(head,sb);
  print(head);
  sb=(struct cla *)malloc(sizeof(struct cla));
 printf("\n输入要插入的数:");
 scanf("%d %s",&sb->num,sb->str);
 }函数

}io

相关文章
相关标签/搜索