首先我们先定义好一个节点
struct node
{
int val;
node * next;
node(int x):val(x),next(nullptr){};
};
创建一个 插入的函数,当node ->val <x时 ,直接插入;当node ->val >x 时交换 node ->val 与 x 的值后再插入
void insertnode(node *&root, int x)
{
//if the list is null ,add the head root
if(root == nullptr )
{
root = new node(x);
return;
}
//
if (root->val <= x )
{
insertnode(root->next ,x );
}else{
int tmp = root->val;
root->val = x ;
insertnode(root->next,tmp);
}
}
这样的话,在插入时就完成了排序的任务,主函数就是读取数据和 输出结果了int main()
{
int n ;
while(cin >n)
{
int x =0 ;
node *root = nullptr ;
for(int i = 0;i< n;i++)
{
cin >> x;
insertnode(root ,x );
}
for(root)
{
cout << root->val<<" ";
root = root->next;
}
cout << endl;
}
return 0;
}



京公网安备 11010502036488号