How does a sentinel node offer benefits over NULL?

后端 未结 5 1273
梦谈多话
梦谈多话 2020-12-07 09:31

On the Sentinel Node wikipedia page it says that the benefits of a sentinel node over NULL are :

  • Increased speed of operations
  • Reduced algorithmic cod
5条回答
  •  情深已故
    2020-12-07 09:48

    There's no advantage with sentinels if you're just doing simple iteration and not looking at the data in the elements.

    However, there's some real gain when using it for "find" type algorithms. For example, imagine a linked list list std::list where you want to find a specific value x.

    What you would do without sentinels is:

    for (iterator i=list.begin(); i!=list.end(); ++i) // first branch here
    {
      if (*i == x) // second branch here
        return i;
    }
    return list.end();
    

    But with sentinels (of course, end actually has to be a real node for this...):

    iterator i=list.begin();
    *list.end() = x;
    
    while (*i != x) // just this branch!
      ++i;
    
    return i;
    

    You see there's no need for the additional branch to test for the end of the list - the value is always guaranteed to be there, so you will automatically return end() if x cannot be found in your "valid" elements.

    For another cool and actually useful application of sentinels, see "intro-sort", which is the sorting algorithm that's used in most std::sort implementations. It has a cool variant of the partition algorithm that uses sentinels to remove a few branches.

提交回复
热议问题