/ / wyszukiwanie węzła na liście pojedynczo połączonej - c ++, lista połączona, lista pojedynczo połączona

wyszukiwanie węzła na liście pojedynczo połączonej - c ++, lista połączona, lista pojedynczo-połączona

Mam pojedynczo połączoną listę składającą się z węzłów o następującej strukturze:

struct date
{
int day, month, year;
};
struct Node
{
string item;
date Exp;
int count;
Node *link;
};
typedef Node* NodePtr;

Kiedy szukam daty wygaśnięcia, wszystkie inne węzły pojawiają się, gdy jej szukam, ale nie pierwszy węzeł. Dzieje się tak, gdy zmieniam także kolejność węzłów. Czy to prosty błąd?

Oto funkcja, której używam do wyszukiwania węzła:

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;
}
}

Odpowiedzi:

1 dla odpowiedzi № 1

Problem jest w twoim stanie while komunikat. Powiedzmy, że szukasz daty 03/21/2013 a pierwszy element, który „zbadasz”, będzie miał datę 04/21/2013. Dni nie są równe, dlatego warunek zostanie oceniony jako false i nawet jeśli istnieje zapis z datą, której szukasz, nigdy go nie osiągniesz.

Ta funkcja może wyglądać następująco:

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;
}

1 dla odpowiedzi nr 2

@LiHO ma w zasadzie rację: twoja logika porównywania jest wadliwa.

Dobrym sposobem na naprawienie tego jest utworzenie operatora porównania 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);
}
};

Wtedy twoja pętla upraszcza się do

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;
}

Ostrzeżenie. niesprawdzone ;-)