第一种,直接在输入数据的时候找到要插入的合适位置。
//版本1
#include "iostream"
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
int n;
cin>>n; //总共有n个数
struct node *head, *p, *q, *r;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
//相当于找到位置插入新的元素
for (int i = 0; i<n; i++)
{
//新节点r
r = (struct node *)malloc(sizeof(struct node));
r->next = NULL;
cin>>r->data; //依次输入n个数
//p、q逐次遍历链表
p = head;
q = p->next;
while (q != NULL && r->data>q->data)
{
q = q->next;
p = p->next;
}
r->next = q;
p->next = r;
}
r = head->next;
while (r != NULL)
{
cout<<r->data;
if (r->next != NULL) cout<<" ";
r = r->next;
}
cout<<endl;
return 0;
}
第二种,链表建立完了之后再排序,中间过程类似于冒泡排序,类似的还可以写成选择排序。
//版本2
#include "iostream"
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head, *tail, *p, *q;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
tail = head;
int n;
cin >> n; //总共n个数
for (int i = 1; i <= n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
cin >> p->data; //依次输入n个数
tail->next = p;
tail = p;
}
struct node *r;
r = head;
//相当于冒泡排序
while (r->next != NULL)
{
p = head->next;
q = p->next;
while (q != NULL)
{
if (p->data>q->data)
{
int t = p->data;
p->data = q->data;
q->data = t;
}
else
{
p = p->next;
q = q->next;
}
}
r = r->next;
}
r = head->next;
while (r != NULL)
{
cout<< r->data;
if (r->next != NULL) cout<<" ";
r = r->next;
}
cout << endl;
return 0;
}