C语言典型例题(二级考试) - 图文

例25 删除指定的节点

struct student *del(struct student *head, long n){structstudent*p1,*p2;/*↑n:要删除学号*/p1=head;

if(p1->num==n)head=p1->next;/*删除首节点*/else

{do{p2=p1;p1=p1->next;

}while(p1!=NULL&&p1->num!=n);if(p1->num==n)p2->next=p1->next;/*找到*/elseprintf(\befound!\\n\/*未找到*/}

free(p1);/*释放被删除节点的存储区*/return(head);/*返回头指针*/}

例26 在链表中插入节点的函数:

structstudent*insert(structstudent*head)

{structstudent*p0,*p1,*p2;longn;intlen;

len=sizeof(structstudent);

p0=(structstudent*)malloc(len);/*申请新节点*/printf(\

scanf(\&p0->num,&p0->score);n=p0->num;/*产生学号副本n*/p1=head;/*从首节点开始查找*/

┇p1=head;/*↓插入在头部*/if(nnum) { p0->next=head; head=p0; }else

{ do /*查找插入位置*/{ p2=p1;

p1=p1->next;

} while(p1!=NULL && n>p1->num);

p0->next=p2->next; /*插入在其余位置*/p2->next=p0;}

return(head);

} /*insert*/

联系客服:779662525#qq.com(#替换为@)