I have the singly linked list consisting of nodes with the following structure:
struct date
{
int day, month, year;
};
struct Node
{
string item;
date Exp;
int count;
Node *link;
};
typedef Node* NodePtr;
When I search for the expiration date, all the other nodes show up when I search for it, but not the first node. This happens when I change the order of the nodes too. Is it a simple mistake?
Here's the function that I use for searching for the node:
NodePtr search_date(NodePtr head, int month, int day, int year)
{
// Point to the head node
NodePtr here = head;
// If the list is empty nothing to search
if (here == NULL)
return NULL;
// Search for the item
else{
//while you have still items and you haven't found the target yet
while (here-> Exp.day != day &&
here-> Exp.month != month &&
here->Exp.year != year &&
here->link != NULL)
here = here->link;
// Found the target, return the pointer at that location
if (here-> Exp.month == month &&
here-> Exp.day == day &&
here-> Exp.year == year)
return here;
// Search unsuccessful, return Null
else
return NULL;
}
}
The problem is in the condition within your while
statement. Let's say that you are looking for the date 03/21/2013
and the first item that you will "examine" will have the date 04/21/2013
. Days are not equal, thus the condition will be evaluated as false
and even if there is a record with the date you are looking for, you'll never reach it.
This function could look like this:
NodePtr search_date(NodePtr node, int month, int day, int year)
{
// while there is some node still:
while (node)
{
// if we found the right node, return it:
if (node->Exp.month == month &&
node->Exp.day == day &&
node->Exp.year == year)
return node;
// move to the next node:
node = node->link;
}
// we haven't found it:
return NULL;
}
@LiHO is basically right : your comparison logic is flawed.
A good way of fixing this is to make a comparison operator for date
struct date
{
int day, month, year;
bool operator==(const date &lhs, const date &rhs)
{
return (rhs.day == lhs.day) && (rhs.month == lhs.month) (rhs.year == lhs.year);
}
};
Then your loop simplifies down to
NodePtr search_date(NodePtr head, const date &wantedDate)
{
for (NodePtr p == head; p != NULL; p = p->link)
if (p.Exp == wantedDate)
return p;
return NULL;
}
Warning. untested ;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.