字母链表

来源:百度文库 编辑:神马文学网 时间:2024/04/26 13:33:11
#include
#include  
#define NULL 0
#define LEN sizeof(struct data)
 struct data
  {int num;
   char elem;
   struct data *next;
   };
int n;/*全局变量*/
struct data *creat(void)/*定义函数,此函数的返回值是head指针*/
    {
    struct data *head,*pf,*pb;
     char e;int d;
     n=0;
   pf=pb=(struct data*) malloc(LEN); /*开辟一个新的单元*/
   printf("input the word and location one by one,like(1,a)\n");
printf("每输完一组按回车,输入(0,a)后按回车接输入完毕\n");
   scanf("%d,%c",&d,&e);
   pb->elem=e;pb->num=d;
   head=NULL;
  while(pb->num!=0)
    {  n=n+1;
     if(n==1)head=pb;
     else pf->next=pb;/*pb后以一个节点*/
          pf=pb;
          pb=(struct data*) malloc(LEN); /*开辟一个新的单元*/
    scanf("%d,%c",&d,&e);
     pb->elem=e;pb->num=d;
        }
   pf->next=NULL;
   return(head);
    }
  void print(struct data *head)/*定义输出链表的函数*/
    {
      struct data *p;
      p=head;
      if(head!=NULL)
      do
        {
  printf("%d %c",p->num,p->elem);
         p=p->next;/*pb后以一个节点*/
        }while(p!=NULL);
     }  struct data *del(struct data *head,int num)/*定义一个删除函数*/
   {
     struct data *pf,*pb;
    if(head==NULL) {printf("这是一个空格链表!!");}
     pb=head;
  while(num!=pb->num&&pb->next!=NULL)/*pb指向的不是要找的节点并且后面还有节点*/
     {pf=pb; pb=pb->next;}/*pb后以一个节点*/
    if(num==pb->num)
    {
     if(pb==head)
     head=pb->next;/*当pb指向的是第一个节点是,把第二个节点的地址赋给head*/
     else
     pf->next=pb->next;
     printf("delete:%d\n",num);
     n-=1;
     }
    else printf("%d  not been found!!\n",num);
    return(head);
    }
  struct data *insert(struct data *head,struct data *p)/*定义一个插入节点的函数*/
   {
     struct data *p0,*p1,*p2;
     p1=head;  /*使得p1指向头指针*/
     p0=p;/*把p0指向要插入的节点*/
      if(head==NULL) /*如果原来是空表*/
      {head=p0;p0->next=NULL;}
      else
      {while((p0->num>p1->num)&&(p1->next!=NULL))
        {
        p2=p1;
        p1=p1->next;/*p1后以一个节点*/
        }
       if(p0->num<=p1->num)
          {
            if(head==p1)head=p0;
             else p2->next=p0;
            p0->next=p1;
          }
       else {p1->next=p0;p0->next=NULL;}/*查到最后的节点*/
       }
    n+=1;/*节点加一*/
    return(head);  
   }
  void main()
{
  struct data *head ,*p;
   int num,d;char e;
printf("请输入字母和它的序位:\n");
head=creat();/*调用创立字母序列*/
print(head);/*调用输出函数*/
printf("请输入你要删除的字母序列num\n");
scanf("%d",&num);
while(num!=0)
{
head=del(head,num);/*调用删除函数*/
print(head);/*调用输出函数*/
printf("请输入你要删除的字母序列num\n");
printf("输入0结束删除\n")
scanf("%d",&num);
}
p=(struct data*) malloc(LEN);
printf("input the word and location one by one,like(1,a)\n");
printf("每输完一组按回车,输入(0,a)后按回车接输入完毕\n");
scanf("%d,%c",&d,&e);
     p->elem=e;p->num=d;
while(p->num!=0)
{
head=insert(head,p);/*调用删除函数*/
print(head);/*调用输出函数*/
p=(struct data*) malloc(LEN);
printf("input the word and location one by one,like(1,a)\n");
printf("每输完一组按回车,输入(0,a)后按回车接输入完毕\n");
scanf("%d,%c",&d,&e);
 p->elem=e;p->num=d;
}
}