簡單的鏈表操做

#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

相關文章
相關標籤/搜索