链表操作

#include <stdio.h>
struct student
{
 long num;
 float score;
 struct student *next;
};
int n;
//create the linklist
struct 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 linklist
void 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 pointer
struct 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 LinkList
struct 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值