单链表的创建、插入、删除、查找

#include 

typedef struct phone
{
  long num;
  char name[20];
  struct phone *next;
} PHONE,*LINK;

LINK crate(int num);
void print(LINK head);
LINK insert(int pos,long num,char *name,LINK head);
LINK del(int pos,LINK head);
void find(long num,LINK head);

int main()
{
  LINK head;
  head=crate(2);
  print(head);
  head=insert(1,1432423,"LIU",head);
  print(head);
  head=del(2,head);
  print(head);
  find(123,head);


}
void print(LINK head)
{
  LINK p=head;
  printf("Record are as follows:\n");
  while(p!=NULL)
  {
  printf("Name:%s Phone:%ld\n",p->name,p->num);
  p=p->next;
  }
  return ;
}

LINK crate(int num)
{
  int i;
  LINK head,p1,p2;
  printf("Enter:name phonenum\n");
  for(i=1;i<=num;i++)
  {
  p2=p1;
  p1=(LINK)malloc(sizeof(PHONE));
  scanf("%s %ld",&p1->name,&p1->num);
  if(i==1)
   head=p1;
  else
  {
   p2->next=p1;
   p2=p2->next;
  }
  }
  p2->next=NULL;
  printf("Crate Done!\n");
  return head;
}


LINK insert(int pos,long num,char *name,LINK head)
{
  LINK p=head,pn;
  int i=0;

  pn=(LINK)malloc(sizeof(PHONE));
  strcpy(pn->name,name);
  pn->num=num;

  while(p!=NULL)
  {
  i++;
  if(pos==1)
  {
  pn->next=head;
  head=pn;
  break;
  }
  else if(i==pos)
  {
 pn->next=p->next;
 p->next=pn;
 break;
  }
  p=p->next;
  }

  return head;

}

LINK del(int pos,LINK head)
{
  LINK p=head,p2=head;
  int i=0;
  while(p!=NULL)
  {
 i++;
    if(pos==1)
 {
 p=p->next;
 free(head);
 head=p;
 break;
 }
 else if(pos==i)
 {
   p2->next=p->next;
   free(p);
   break;
 }
 p2=p;
 p=p->next;
  }

  return head;

}


void find(long num,LINK head)
{
  LINK p=head;
  while(p!=NULL)
  {
  if(p->num==num)
  {
   printf("Found!Record:%s,%ld",p->name,p->num);
   return ;
  }
  p=p->next;
  }
  printf("Not found");

}

Leave a Reply

Your email address will not be published. Required fields are marked *