CLRS10.2-4练习 - 修改链表查询方法

要求:

As written, each loop iteration in the LIST-SEARCH' procedure requires two tests:
one for x ≠ L.nil and one for x.key ≠ k. Show how to eliminate the test for
x ≠ L.nil in each iteration.

解法:

关键就是在while循环开始之前将哨兵sentinel的key值设为k,这样while循环无论链表中是否查询成功都会终止

伪代码

LIST-SEARCH'(L, k)

1 L.nil.key = k

2 x = L.nil.next

3 while x.key ≠ k

4   x = x.next

5 if x == L.nil

6   L.nil.key = NIL

7 return x

posted @ 2017-10-12 13:23  Terry Zhang  阅读(135)  评论(0编辑  收藏  举报