链表操作

    技术2022-05-11  64

    #include <stdio.h>struct student{ long num; float score; struct student *next;};int n;//create the linkliststruct student *creat(){ struct student *head; struct student *pTear,*pCur; n=0; head=NULL; pTear=pCur=new student; scanf("%ld,%f",&pCur->num,&pCur->score); while(pCur->num!=0) {  n+=1;  if(n==1)   head=pCur;  else   pTear->next=pCur;  pTear=pCur;  pCur=new student;  scanf("%ld,%f",&pCur->num,&pCur->score);   } pTear->next=NULL; delete pCur; return head;}//print the linklistvoid print(struct student *p){ while(p!=NULL) {  printf("%ld,%5.1f/n",p->num,p->score);  p=p->next; }}//delete a student by num //return the head pointerstruct student *del(struct student *head,long num){ struct student *pre,*pcur; if(head==NULL) {  printf("list is empty/n");  return NULL; } pcur=head; while(pcur->num!=num && pcur->next!=NULL) {  pre=pcur;  pcur=pcur->next; } if(pcur->num==num) {  if(pcur==head)  {   head=pcur->next;  }  else  {   pre->next=pcur->next;  }  delete pcur;  printf("delete:%ld/n",num);  n=n-1; } else  printf("%ld not been found!/n",num);   return head;}//insert a student into the LinkListstruct student * insert(struct student *head,struct student *pin){ struct student *pcur,*pre; pcur=head; if(head==NULL)  //空插 {  head=pin;     pin->next=NULL;  return head; } while((pcur->num<pin->num)&&pcur->next!=NULL) {  pre=pcur;  pcur=pcur->next; } if(pcur->num>=pin->num) {  if(head==pcur)   //头插  {   head=pin;     }  else  {   pre->next=pin;  }  pin->next=pcur; } else {  pcur->next=pin;  pin->next=NULL; } n+=1; return head;

    }void ExeLinkList(){ struct student *head,*stu;long del_num;printf("input records:/n");head=creat();printf("Before del:/n");print(head);printf("/n input the deleted number:");scanf("%ld",&del_num);head=del(head,del_num);printf("After del:/n");print(head);while(getchar()!='*'){printf("Insert a record!/n");stu=new student;scanf("%ld,%f",&(*stu).num,&(*stu).score);head=insert(head,stu);printf("After insert!");print(head);} 


    最新回复(0)