i need help with this. im suppose to remove a duplicate from a link list once user enter.
this is the code to find duplicate
1 2 3 4 5 6 7 8 9 10 11 12 13
Node* cur = head;
int size = SortedGetLength(), count = 1;
while (count <= size) {
if (cur->data == x) {
returntrue;
delete cur;
}
else
cur = cur->next;
count++;
}
returnfalse;
this is some part of my main which i think its causing the problem (its not all of my main)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while (choice != "e")
{ //loops commands until "Exit"
if (m.sortedIsEmpty() == true && choice != "i")
{
//checks if List is empty before commands
cout << "List is empty" << endl;
}
else { //the rest format according to the command
if (choice == "i")
{
cin >> x;
if (samenumber == "n")
{
if (m.Duplicate(x))
cout << "You cant have more than one same number";
whenever i try to insert a number into a list and print it out, it would say list is empty i wonder wat is wrong but i coudnt figure it out. Any help is appreciated
In other words, you don't need to find duplicates.
You don't need to, because by definition there are never any.
There are never any, because you will not insert any.
What you actually do want to find is point of insertion (POI).
When you do have a new value X, you want to find the last node POI, where POI.data < X (assuming ascending order).
When you have found POI, there are three possibilities:
1. POI.next is null: no duplicates, append new node(X)
2. POI.next->data == X: duplicate, no action
3. X < POI.next->data: no duplicate, insert new node(X) between POI and POI.next
However, before all that you have two trivial cases to test:
1. head is nullptr
2. X < head->data
Both require insertion to the beginning of the list (with tiny difference).