一、作用
1、减少判断,提高时间效率
2、简化边界条件,使整体逻辑统一
二、例子
1、在一个无序的列表a中找一个元素e(不一定能找到)
未使用哨兵:
for (int i = 0; i < a.size(); i++) {
if (a.get(i) == e) {
return i;
}
}
return -1;
使用哨兵
int n = a.size();
a.add(e);
int i = 0;
while(a.get(i) != e) i++;
if (i < n) return i;
else return -1;
这里的哨兵的作用就是让程序在遍历列表的时候不需要每前进一格就去检查是否越界,因为哨兵就在边界拦着。
2、经典案例:往一个链表表头位置插入一个元素
class Node {
int val;
Node next;
}
class LinkedList {
Node head;
}
没有哨兵写法
insert(LinkedList list, Node x) {
if (list.head == null) {
list.head = x;
} else {
x.next = list.head;
list.head = x;
}
}
加入哨兵,我们把head作为一个哨兵,里面不存val,只存next。这样插入时就不需要对head判空处理
insert(LinkedList list, Node x) {
x.next = list.head.next;
list.head.next = x;
}
这种例子java还真不好想到(饶了半天),链表操作还是C++指针来的更直观。