對一個存儲學生信息的單向鏈表,按照學號升序對鏈表進行排序,每個節點包含了一個學生ID

1.	問題描述: 
(1)建立單向鏈表,每個結點包括:學號,姓名,性別。(2)按照學號對該鏈表進行升序排序,要求採用冒泡法,而後進行輸出。在主函數中分別調用創建、排序和輸出函數。2.	問題的解決方案:根據問題描述,首先創建鏈表,不僅要給各個結點輸入數據,更重要的是要建立起前後結點相互聯結的關係。可同時設置3個指針變量,head、p、q,它們都是結構類型的指針,分別代表表頭、新建結點和表尾結點。使用new操作符開闢新的存儲空間,用來存放新結點。而後對該鏈表進行升序排列,排序時指針要進行互換,沒有數據交換時進行結點的訪問。四、主要技術問題的描述根據三的分析,主要問題在於鏈表的創建以及排序過程中指針的指向。如需要創建N=5個結點,if(i==1)    head=p1;     //將鏈表中第一個新建結點作爲表頭elsep2->next =p1;p2=p1;p1=new(STUDENT);cin>>p1->stu_number >>p1->name >>p1->sex >>p1->age;    p2->next =NULL;   //最後一個結點的next成員不指向任何結點排序時,設置三個結構指針m、s、p來記錄位置,m=head;	p=head->next;	s=p->next;若不需要交換,指針依次向後移動:m=p; p=s;s=s->next;如果需要進行交換,則:p->next=s->next;     s->next=p;m->next=s;m=s;s=p->next;將兩個非遞減的鏈表合併成一個新的非遞減的鏈表。

#include <iostream>
#include <string>
using namespace std;
typedef struct node
{
char ID[20];
char name[30];
char gender[10];
int age;
node *next;
}student;
void print(student *head)
{
student *p=head;
while(p->next != NULL)
{
cout<<p->next->ID<<" "<<p->next->name<<" "<<p->next->gender<<" "<<p->next->age<<endl;
p=p->next;
}
cout<<endl;
}
void create(student *head)
{
cout<<"請依次輸入學生的學號 姓名 性別 年齡,輸入學號爲#時結束"<<endl;
char ID[20];
student *p=head;
while(1)
{
cin>>ID;
if(strcmp(ID,"#")==0)
break;
student *q=new student();
strcpy(q->ID,ID);
cin>>q->name>>q->gender>>q->age;
q->next=p->next;
p->next=q;
p=q;
}
cout<<"鏈表創建完成!"<<endl<<endl;
}
void sort(student *head)
{
student *m=head;
if(head->next==NULL || head->next->next==NULL)
{
cout<<"鏈表排序完成!"<<endl<<endl;
return;
}
student *p=head->next;
student *s=p->next;
student *k=NULL;
while(k != head->next->next)
{
while(s!=k)
{
if(strcmp(p->ID,s->ID) > 0)
{
p->next=s->next;     
s->next=p;
m->next=s;
m=s;s=p->next;
}
else
{
m=p;
p=s;
s=s->next;
}
}
k=p;
m=head;
p=m->next;
s=p->next;
}
cout<<"鏈表排序完成!"<<endl<<endl;
}
int main()
{
int order;
student *head=new student();
head->next=NULL;
while(1)
{
cout<<"請輸入命令序號:"<<endl<<"1.創建鏈表"<<endl<<"2.排序鏈表"<<endl<<"3.輸出鏈表"<<endl<<"4.退出"<<endl;
cin>>order;
switch(order)
{
case 1:create(head);break;
case 2:sort(head);break;
case 3:print(head);break;
case 4:return 0;
}
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章