#include <iostream>
using namespace std;
typedef struct Linklist
{
int data;
struct Linklist* next;
}Linknode,*linklist;
void creatnewlink(linklist& L, int n)
{
L = new Linknode;
L->next = NULL;
linklist p = L;
for (int i = 0; i < n; i++)
{
int e;
cin >> e;
linklist s = new Linknode;
s->data = e;
s->next = p->next;
p->next = s;
p = s;
}
}
//直接插入排序的链表表现形式
void straighrinsertsort(linklist& L)
{
linklist s, p, q; // 定义三个指针变量s、p、q
int t; // 定义一个整型变量t
if (L == NULL || L->next == NULL) // 如果链表L为空或只有一个节点,则直接返回
return;
else
for (q = L, p = L->next; p != NULL; p = q->next) // 遍历链表,从第二个节点开始
{
for (s = L; s != q->next; s = s->next) // 在已排序部分中寻找插入位置
if (s->data > p->data) // 如果找到插入位置,则跳出循环
break;
if (s == q->next) // 如果s指向已排序部分的末尾(即p应该插入到最后)
q = p;
else // 否则,需要将p插入到s之前
{
q->next = p->next; // 断开p节点
p->next = s->next; // 将p节点插入到s之前
s->next = p; // s指向p
t = p->data; // 交换p和s的data域
p->data = s->data;
s->data = t;
}
}
}
void print(linklist& L)
{
linklist p;
p = L->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
int main()
{
linklist L;
int n;
cin >> n;
creatnewlink(L, n);
straighrinsertsort(L);
print(L);
return 0;
}
06-26
427
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-21
479
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-22
948
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-24
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交