雙向鏈表C語言

鏈表結構定義

typedef struct node
{
  char  data[19+1];
  struct node *llink;
  struct node *rlink;/*上一個,下一個*/
};

/*創建鏈表*/

int creat_list(struct node *h)
{
   /*
  if((h=(struct node *)malloc(sizeof(struct node)))==NULL)
  {
   printf("不能分配內存空間!");
   return -1;
  }*/
  h->data[0]='/0';
  h->llink=NULL;
  h->rlink=NULL; 
  return 1;
}
/*清空鏈表*/
int free_list(struct node *h)
{
   struct node *p,*s;
   p=h->rlink;
   while(p!=NULL)
   {
     s=p;
     free(p);
     p=s->rlink;
   }
   return 1;
}
/*查找數據*/
int find_list_data(struct node * h,char *elem)
{
  struct node *p;
  char *y=NULL;
  if(h==NULL)
  {
   return -1;
  }
  p=h->rlink;
  while(p!=NULL)/*鏈表尾*/
  {
    y=p->data;
    if(strncmp(y,elem,18)==0)/**/
    {
     
      return 1;
    }
    else
    {
      p=p->rlink;
    }
  }
  return 0;
}
/*刪除數據*/
int del_list_data(struct node * h,char *elem)
{
  struct node *p,*l;
  char *y;
   if(h==NULL)
     return -1;
  
  p=h->rlink;
  while(p!=NULL)  /*鏈表尾*/
  {
    y=p->data;
    if(strncmp(y,elem,18)==0)/**/
    {
      l=p->llink;        
      l->rlink=p->rlink;
      free(p);
      return 1;
    }
    else
    {
      p=p->rlink; 
    }
  }
  return 0;
}

/*增加數據*/
int add_list_data(struct node *h,char *elem)
{
   struct node *s,*t;
   if(h==NULL)
     return -1;
   if((s= (struct node *)malloc(sizeof(struct node)))==NULL)
   {
    printf("不能分配內存空間!");
    return -1;
   }
   strncpy(s->data,elem,18);  
   s->llink=h;
   if(h->rlink==NULL)/*鏈表爲空*/
   {
      h->rlink=s;
      s->rlink=NULL;    
   }
   else
   {
     s->rlink=h->rlink;
     h->rlink->llink=s;
      h->rlink=s; 
   }
   return 1;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章