How can I sort a singly linked list in constant space?(如何在恒定空间中对单链表进行排序?)
问题描述
我有一个单向链表,由于内存限制,我需要在恒定空间中对其进行排序(换句话说,不应使用与列表中项目数成正比的额外空间).
I have a singly linked list and I need to sort it in constant space due to memory limitations (in other words, no extra space should be used that is proportional to the number of items in the list).
链表的结构为:
head.item
= 要排序的有效负载;和head.next
= 下一项.
head.item
= the payload you want to sort on; andhead.next
= the next item.
对于我构建另一个列表的恒定空间折扣解决方案的要求,我需要就地完成.
The requirement for constant space discounts solutions where I build another list, I need to do it in-place.
我该怎么做?
推荐答案
在常量空间中对链表进行排序很容易,只需调整指针即可.最简单的方法是使用只交换相邻元素的排序算法.我将提供一个冒泡排序,只是因为你对效率没有要求:
Sorting a linked list in constant space is easy, you just have to adjust the pointers. The easiest way to do this is to use a sort algorithm that only swaps adjacent elements. I'm going to provide a bubble-sort, just because you've made no requirement for efficiency:
# Enter loop only if there are elements in list.
swapped = (head <> null)
while swapped:
# Only continue loop if a swap is made.
swapped = false
# Maintain pointers.
curr = head
next = curr.next
prev = null
# Cannot swap last element with its next.
while next <> null:
# Swap if items in wrong order.
if curr.item > next.item:
# Notify loop to do one more pass.
swapped = true
# Swap elements (swapping head is special case).
if curr == head:
head = next
temp = next.next
next.next = curr
curr.next = temp
curr = head
else:
prev.next = curr.next
curr.next = next.next
next.next = curr
curr = next
endif
endif
# Move to next element.
prev = curr
curr = curr.next
next = curr.next
endwhile
endwhile
这篇关于如何在恒定空间中对单链表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在恒定空间中对单链表进行排序?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01