单链表的排序
【基本要求】:
(1)一单链表中元素无序,编写算法将之排成有序序列;
(2)要求只在原有链表上操作,不单独分配空间。
使用标准C++
一单链表中元素无序,编写算法将之排成有序序列
答案:3 悬赏:70
解决时间 2021-11-25 22:01
- 提问者网友:
- 2021-11-24 23:28
最佳答案
- 二级知识专家网友:浪女动了心
- 2021-11-25 00:09
由冒泡排序得到启示,每趟均从头节点开始扫描,比较相邻两节点的数据,
满足特定要求时进行节点交换。
需要注意的是,必须有一个指针保存当前节点的前一个位置,这样在交换
节点后链表不会断开;并且要指定一个哨兵节点作为每趟比较的终结点,该哨
兵节点实际上就是有序区的首节点。
struct Node {
int data;
Node *next;
};
void listSort(Node **head)
{
if(head == NULL || *head == NULL)
return;
Node *cur, *post, *pre, *sentinel = NULL; // sentinel 标记有序区的首个节点
bool sorted;
do {
pre = NULL;
cur = *head;
sorted = true;
while((post = cur->next) != sentinel) {
if(cur->data > post->data) {
sorted = false; // 发生交换,则仍未有序
cur->next = post->next;
post->next = cur;
if(pre != NULL)
pre->next = post;
pre = post;
if(cur == *head)
*head = post; // 保证头指针指向最小的节点
} else {
pre = cur;
cur = post;
}
}
sentinel = cur; // cur 为该趟排好序的节点
} while(!sorted); // 若未发生交换,则已经有序
}
满足特定要求时进行节点交换。
需要注意的是,必须有一个指针保存当前节点的前一个位置,这样在交换
节点后链表不会断开;并且要指定一个哨兵节点作为每趟比较的终结点,该哨
兵节点实际上就是有序区的首节点。
struct Node {
int data;
Node *next;
};
void listSort(Node **head)
{
if(head == NULL || *head == NULL)
return;
Node *cur, *post, *pre, *sentinel = NULL; // sentinel 标记有序区的首个节点
bool sorted;
do {
pre = NULL;
cur = *head;
sorted = true;
while((post = cur->next) != sentinel) {
if(cur->data > post->data) {
sorted = false; // 发生交换,则仍未有序
cur->next = post->next;
post->next = cur;
if(pre != NULL)
pre->next = post;
pre = post;
if(cur == *head)
*head = post; // 保证头指针指向最小的节点
} else {
pre = cur;
cur = post;
}
}
sentinel = cur; // cur 为该趟排好序的节点
} while(!sorted); // 若未发生交换,则已经有序
}
全部回答
- 1楼网友:木子香沫兮
- 2021-11-25 01:01
你好!
哥,这是最最基础的链表操作,看看冒泡排序,自己在编译器里练练吧,别来这找Copy代码
如有疑问,请追问。
- 2楼网友:情战凌云蔡小葵
- 2021-11-25 00:51
std::sort(list.begin(), list.end());
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯
• 手机登qq时,显示手机磁盘不足,清理后重新登 |
• 刺客的套装怎么选啊? |