用链表来实现学生信息的存储

链表是线性表的链式存储结构,有单链表、循环单链表、双链表、循环双链表、顺序链表。

链表不能够进行随机访问,但在插入和删除数据时不需要移动元素,比顺序结构操作简单。

简单程序实现:

#include
#include
using namespace std;
struct student//建立学生信息链表结构体
{
  int num;
  float score;
  struct student *next;

};
void ScIn(student *s1)//输入学生数据信息
{
 cout<<"please input the student information: "<  cout<<"the number is: "<  cin>>s1->num;
 cout<<"the score is: "<  cin>>s1->score;
}
//使用头插法来创建带有头结点的链表,并需要返回头节点的指针
struct student * Creat(student *L,int n)
{  
   L=(student*)malloc(sizeof(student));
   if(!L)cout<<"error!"<    else L->next=NULL;
for(int i=1;i<=n;i++)
   {
       student *s;
       s=(student*)malloc(sizeof(student));
  if(!s)cout<<"error!";
  cout<<"please input the data of this students: " <  ScIn(s);
  s->next=L->next;
  L->next=s;
   }
return L;
}

//插入新的学生信息
void Insert(student *head,int i)
{ int j=0;
student *q=head;
       student *sa;
sa=(student*)malloc(sizeof(student));
while(q->next && j{
q=q->next;
       j++; 
   }
if(!q->next||j>i)cout<<"the alloation is wrong!"<       else 
{ScIn(sa);
sa->next=q->next;
q->next=sa;}
}

//删除指定位置的学生节点
void Delete(student *head,int i)
{ int j=0;
student *p=head;
  while(p->next && j{
p=p->next;
       j++; 
   }
if(!p->next||j>i)cout<<"the alloation is wrong!"< }

//显示学生信息表
void Show(student *head)
{  cout<<"show information of students: "<    cout<<"num        score     " <    student *p=head->next;
    while(p!=NULL)
   {
  cout<num<<"      "<score<  p=p->next;
   }

}

//主程序
void main()
{  int m=0;
   int a=0;
   int n=0;
  student *l=0;
  student *head=0;
  cout<<"please input the number of student "<   cin>>m;
  head=Creat(l,m);
  Show(head);
  cout<<"please input the alocation you want to insert: "<   cin>>a;
  Insert(head,a);
  Show(head);
  cout<<"please input the alocation you want to delete: "<   cin>>n;
  Delete(head,n) ;
  Show(head);
}

你可能感兴趣的:(数据结构与算法,C++)