Originally Posted by
Athul
What I don't understand is how the author getting the answer. Have you seen the video???
As I mentioned earlier, I could not access your video. Now that I see it... oh gosh, you mean he actually wrote:
Code:
temp = head.first;
if (temp == (LISTITEM*)&head) // if the head of the queue points to itself ...
This is a terrible idea. LISTITEM and LISTHDR are entirely different structs, so one should not be routinely casting between pointers to them. I don't think the author is actually "getting the answer": the address of head is likely to be the address of its member named first, but that is fundamentally different from the address stored in that member, i.e., the value of head.first. Consequently, if he appears to be "getting the answer", he might be faking it, or perhaps the code that he actually tested is different from what he showed in the video. Either way, I would not recommend this tutorial at all.
What you should be doing is stuff like:
because if you code this sensibly, then when the queue is empty, both head.first and head.last will be null pointers.
EDIT:
OHHH... I see now. Look at enqueue:
Code:
item->next = (LISTITEM*)&head;
What this tutorial is doing is basically using (LISTITEM*)&head as a sentinel value, i.e., a special value that denotes the end, but otherwise is not a valid value. It makes no sense, but that's what they are doing. The usual approach is to write: