1. 程式人生 > >用連結串列來實現學生資訊的儲存

用連結串列來實現學生資訊的儲存

連結串列是線性表的鏈式儲存結構,有單鏈表、迴圈單鏈表、雙鏈表、迴圈雙鏈表、順序連結串列。

連結串列不能夠進行隨機訪問,但在插入和刪除資料時不需要移動元素,比順序結構操作簡單。

簡單程式實現:

#include<iostream>
#include<stdlib.h>
using namespace std;
struct student//建立學生資訊連結串列結構體
{
  int num;
  float score;
  struct student *next;

};
void ScIn(student *s1)//輸入學生資料資訊
{
 cout<<"please input the student information: "<<endl;
 cout<<"the number is: "<<endl;
 cin>>s1->num;
 cout<<"the score is: "<<endl;
 cin>>s1->score;
}
//使用頭插法來建立帶有頭結點的連結串列,並需要返回頭節點的指標
struct student * Creat(student *L,int n)
{  
   L=(student*)malloc(sizeof(student));
   if(!L)cout<<"error!"<<endl;
   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: "<<endl;
  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<i-1)
{
q=q->next;
       j++; 
   }
if(!q->next||j>i)cout<<"the alloation is wrong!"<<endl;
      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<i-1)
{
p=p->next;
       j++; 
   }
if(!p->next||j>i)cout<<"the alloation is wrong!"<<endl;
}

//顯示學生資訊表
void Show(student *head)
{  cout<<"show information of students: "<<endl;
   cout<<"num        score     " <<endl;
   student*p=head->next;
    while(p!=NULL)
   {
  cout<<p->num<<"      "<<p->score<<endl;
  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 "<<endl;
  cin>>m;
  head=Creat(l,m);
  Show(head);
  cout<<"please input the alocation you want to insert: "<<endl;
  cin>>a;
  Insert(head,a);
  Show(head);
  cout<<"please input the alocation you want to delete: "<<endl;
  cin>>n;
  Delete(head,n) ;
  Show(head);
}