identifying duplicate values in linked list C++ -
i want identify ones , how many values duplicate in linked list user's input. , code wrote it:
int count; int compare, compare2; (p = first; p != null; p = p->next){ compare = p->num; (j = first; j != null; j = j->next){ if (compare == j->num){ compare2 = j->num; count++; } } if (count > 1){ cout << "there @ to the lowest degree 2 identical values of: " << compare2 << " repeat for: " << count << "times" << endl; } }
basically thought of take first element in first loop , compare elements in sec loop , count if there cases of them beingness similar, , print result after - take next element , on.
however output elements , doesn't count correctly either. i'm lost @ how adjust it.
i tried using same p variable in both loops same list want loop, .exe failed i'd finished input.
i saw few examples around there function deleting duplicate values, comparing part run through while loop, , i'm wondering - doing wrong on one?!
your logic flawed since both p
, j
iterate on entire list. when p == j
, values bound match.
change block
if (compare == j->num){ compare2 = j->num; count++; }
to
if (p != j && compare == j->num){ compare2 = j->num; count++; }
also, don't need line
compare2 = j->num;
since compare2
equal compare
.
you can cut down number of tests changing inner loop bit. then, won't need p != j
bit either.
(j = p->next; j != null; j = j->next){ if (compare == j->num){ count++; } }
c++ linked-list duplicates
No comments:
Post a Comment