我假设链接列表进行排序 - 否则它不能在基于比较算法来完成,因为你需要它Omega(nlogn)
- 迭代排序的“最高水平”列表中,并且每隔一个节点添加一个“链接节点”。
- 重复,直到最高级别只有一个节点。
这个想法是生成一个新的列表,原始大小的一半,它链接到原始的每个第二链接,然后递归调用小列表,直到你到达一个大小为1的列表
您最后将列出大小为1,2,4,...,n/2的链接。
伪代码:
makeSkipList(list):
if (list == null || list.next == null): //stop clause - a list of size 1
return
//root is the next level list, which will have n/2 elements.
root <- new link node
root.linkedNode <- list //linked node is linking "down" in the skip list.
root.next <- null //next is linking "right" in the skip list.
lastLinkNode <- root
i <- 1
//we create a link every second element
for each node in list, exlude the first element:
if (i++ %2 == 0): //for every 2nd element, create a link node.
lastLinkNode.next <- new link node
lastLinkNode <- lastLinkNode.next //setting the "down" field to the element in the list
lastLinkNode.linkedNode <- node
lastLinkNode.next <- null
makeSkipList(root) //recursively invoke on the new list, which is of size n/2.
复杂性是因为算法复杂度可以描述为T(n) = n + T(n/2)
为O(n),这样你可以获得T(n) = n + n/2 + n/4 + ... -> 2n
这是很容易看到它不能做的更好然后O(n)
,因为至少你将不得不在原始列表的后半部分添加至少一个节点,并且到达那里本身是O(n)
请参阅[wiki页面](http://en.wikipedia.org/wiki/Skip_list),了解您提到的随机算法 – HelloWorld 2012-04-28 19:29:35