题目描述
根据输入,采用尾插法创建链表。对创建的链表使用冒泡排序进行降序排序,输出排序后的链表。
说明:程序中不可见数组、容器,否则计0分。
输入
测试次数t
每组测试数据格式为:
数据个数n
n行,每行一个字符串
输出
对每组测试数据,输出字符串按字典降序排序后的链表。各组输出间以空行分隔。
样例输入
2
4
shenzhen
nan
jing
beijing
wuhan
6
china
brazil
germany
philippines
switzerland
singapore
样例输出
wuhan
shenzhen
nanjing
beijing
switzerland
singapore
philippines
germany
china
brazil
代码实现:
#include <iostream> #include <cstdio> using namespace std; struct node{ string str; node *next; }; void CreateList(node *head) { node *tail=head; int data; int n,i; cin>>n; getchar(); for(i=0;i<n;i++){ node *s=new node;//创建新的节点 cin>>s->str; s->next=NULL; tail->next=s;//将新结点插入链表中 tail=s; } } void ShowList(node *head) { node *display=head->next; while(display){ cout<<display->str<<endl; display=display->next; } cout<<endl; } void bubblesort(node *head) { node *cur=NULL; node *teil=NULL; cur=head->next; while(cur!=teil){ while(cur->next!=teil){ if(cur->str<cur->next->str){ string temp=cur->str; cur->str=cur->next->str; cur->next->str=temp; } cur=cur->next; } teil=cur; cur=head->next; } } int main() { int t; cin>>t; while(t--){ node *head=new node; head->next=NULL; CreateList(head);//创建 bubblesort(head); ShowList(head); } return 0; }