#include <iostream>
using namespace std;
void insert(double);
void remove(double);
void print();
struct db{
double num;
struct db *next;
};
db *head=NULL;
int main()
{
db *head=NULL;
insert(2.5);
insert(2.2);
insert(7.8);
remove(2.2);
insert(2.3);
insert(11.2);
print();
}
void insert(double num)
{
db *cur, *tmp, *p;
int i;
if (head==NULL) //we are creating first element of list
{
head= new db;
head->num=num;
head->next=NULL;
return;
};
cur=head;
tmp=head;
while(cur->next !=NULL)
{
if(num > cur->next->num) //we comparing num with every next num object on list
{
tmp=cur; //saves cur to tmp, which we will use to add element
i++; //iterator, used to define if our num is bigger than some element on list or not, if its=0 than we going to create new head
if(cur->next->num==num)
{
return;
}
}
cur=cur->next; //loop progress
}
cur=tmp; //we creating new element, and if i=0 than we assigning head to it, otherwise we inputing it in middle
p=new db;
p->num=num;
if (p->num == head->num) //if head=num we are breaking function
{
return;
}
p->next=tmp->next;
if(i==0)
{
head=p;
} else {tmp->next=p;}
return;
}
void remove(double num)
{
db *cur;
cur=head;
if(cur->num==num)
{
head=cur->next;
delete cur;
}
while(cur!=NULL)
{
if(cur->next->num==num)
{
db *tmp;
tmp=cur->next;
cur=tmp->next;
delete tmp;
}
}
}
void print()
{
db *cur;
cur=head;
while(cur->next !=NULL)
{
cout<<cur->num,"\n";
cur=cur->next;
}
}
Komentowałem w j.Angielskim, problem jest w tym ze funkcja print albo nie wypisuje, albo insert nie dopisuje liczb do listy, chociaż wygląda mi poprawnie kod. Dodam dla tych co nie zauważą po kodzie że lista ma dodawać liczby sortując je od razu.
na krotko opisze funkcje insert. Sprawdzamy czy lista istnieje, jesli nie to ją tworzymy, następnie przechodzimy całą listę szukając w którym miejscu nasza liczba będzie mniejsza od następnej, gdy znajdziemy ją to kończymy pętle, a w tmp zapisujemy wskaźnik do poprzedniej. Tworzymy nowy element któremu każemy wskazywać na następny, a poprzedniemu na nowy. Do tego na końcu są 2 if'y które mają za zadanie wyjść z funkcji jeżeli okaże się że insert musiałby wstawić 2 takie same liczby obok siebie.