还是c链表

用VC6.0写的,输入输出用到了C++的,其他的都是C的。
一个链表程序,支持建立,插入,删除,输出;学生的学号和分数
#include <iostream.h>
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct stu)
#define BY (struct stu *)malloc(LEN)
typedef struct stu STU;
struct stu
{
 long int num;
 float score; 
 struct stu *next;
};
int n;
struct stu *creat()//建立链表
{
 struct stu *p2,*p1,*head;
 n=0;
 p1=p2=BY;
 cin>>p1->num>>p1->score;
 head=NULL;
 for(;p1->num!=NULL;)
 {
  n+=1;
  if(n==1) head=p1;
  else p2->next=p1;
  p2=p1;
  p1=BY;
  cin>>p1->num>>p1->score;
 }
 p2->next=NULL;
 return head;
}
void print(struct stu *head)//查询链表
{
 struct stu *p;
 cout<<"putout the students' number and score:\n";
 p=head;
 for(;p!=NULL;)
 {
  cout<<"number:"<<p->num<<"\tscore:"<<p->score<<endl;
  p=p->next;
 }
}

STU  *insert(STU *head,STU *std)//插入链表
{
 STU *p0,*p1,*p2;
 
 p1=head;
 p0=std;
 if(head==NULL)
 {
  head=p0;
  p0->next=NULL;

 }
 else 
 {
  while((p0->num>p1->num)&&(p1->next!=NULL))
  {
   p2=p1;
   p1=p1->next;
  }
  if(p0->num<=p1->num)
  {
   if(head==p1)head=p0;
   else p2->next=p0;
   p0->next=p1;
  }
  else
  {
   p1->next=p0;
   p0->next=NULL;
  }
 }
 n+=1;
 return head;
}

STU *dele(STU *head,long int num)//删除链表
{
 STU *p1,*p2;
 if(head==NULL)
 {cout<<"empty list!\n";goto end;}
 p1=head;
 while(p1->num!=num&&p1->next!=NULL)
 {p2=p1;p1=p1->next;}
 if(p1->num==num)
 {if(p1==head)head=p1->next;
 else p2->next=p1->next;
 n=n-1;
 free(p1);
 }
 else cout<<"the node not been found!\n";
end:
 return head;
}



int main(int argc, char* argv[])
{
 struct stu *cl,*stud;
 long int num;
 int i;

  cout<<"*************************************************\n"
   <<endl
   <<"selet the item                    *****\n"
   <<"1:set the students' resoure       *****\n"
   <<"2:query the students' resoure     *****\n"
   <<"3:insert the students' resoure    *****\n"
   <<"4:delete the students' resoure    *****\n"
   <<"0:ESC the program!                *****\n"
   <<endl
   <<"************************************************\n";
   do
 {
  cout<<"select the number to next\n";
  cin>>i;
  switch(i)
  {
  case 1:
   {
    cout<<"Please input the students' number and score:"<<endl
     <<"number\tscore"<<endl;
    cl=creat();
   }break;
  case 2:
   {
    cout<<"number\tscore"<<endl;
    print(cl);
   }break;
  case 4:
   {
    cout<<"input the delete number:\n";
    cin>>num;    
    cl=dele(cl,num);

   }break;
  case 3:
   {
    cout<<"input the insert number and score:\n";
    stud=BY;
    cin>>stud->num>>stud->score;
    cl=insert(cl,stud);

   }break;
  case 0: break;
  default:cout<<"input err\n";break;
  }
 }while(i!=0);

 
 return 0;
}
阅读更多
想对作者说点什么? 我来说一句

C语言实现链表

2011年08月26日 16KB 下载

C语言链表知识资料

2013年06月05日 2.17MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭