算法中的哨兵

一、作用

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++指针来的更直观。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值