You are on page 1of 3

#include <iostream>

using namespace std;

// Napisać funkcję, która z listy jednokierunkowej zaczynającej się pod jakimś


adresem i
// zawierającej liczby rzeczywiste, dopisuje na początku listy element zawierający
średnią
// wartości wszystkich dodatnich elementów listy (o ile takie są), po czym usuwa
element
// o jakimś kolejnym numerze (o ile istnieje) i zwraca informację logiczną, czy
nastąpiło
// usunięcie.
// Uwaga: słowo jakiś oznacza parametr funkcji.

struct Elem{
double liczba;
Elem *next;
};

void tworz(Elem *&glowa){

glowa=NULL;

double x;

cin>>x;

if(glowa==NULL){
glowa=new Elem;
glowa->liczba=x;
glowa->next=NULL;
}

Elem *ogon=glowa;

cin>>x;
while(x!=0){
ogon->next=new Elem;
ogon=ogon->next;
ogon->liczba=x;
ogon->next=NULL;
cin>>x;
}

bool funkcja(Elem *&glowa, int nr){


Elem *pom=glowa;
if(glowa==NULL){
return false;
}
bool dodatnie=true; // zmienna ktora mowi czy lista ma dodatnie elementy
double suma=0;
int i=0;
double srednia=0;

while(pom!=NULL){
if(pom->liczba>0){
dodatnie=true;
suma+=pom->liczba;
i++;
}
else if(pom->liczba<=0){
dodatnie=false;
}
pom=pom->next;
}

if(dodatnie==true){
srednia=suma/i;
Elem *nowy=NULL;
nowy = new Elem;
nowy->liczba=srednia;
nowy->next=glowa;
glowa=nowy;
}else{
cout<<"Nie bylo elementow dodatnich!" <<endl;
}
//usuwanie

int licz=0;
pom=glowa;

while(pom!=NULL){
licz++;
pom=pom->next;
}

if(nr<=0 || nr>licz){
return false;
}

if(nr==1){
Elem *del=glowa;
glowa=glowa->next;
delete del;
}else{
Elem *del=glowa;
for(int i=1; i<nr-1; i++){
del=del->next;
}
Elem *u=del->next;
del->next=u->next;
delete u;

return true;
}

void drukuj(Elem *glowa){


while(glowa!=NULL){
cout<<glowa->liczba<<endl;
glowa=glowa->next;
}
}

void kasuj(Elem *&glowa){


Elem *tmp;
while(glowa!=NULL){
tmp=glowa->next;
delete tmp;
glowa=tmp;
}

int main()
{
Elem *glowa;

tworz(glowa);
cout<<endl;
cout<<"Lista na poczatku: "<<endl;
drukuj(glowa);

cout<<endl;
int nr;
cout<<"Podaj nr elementu do usuniecia: "<<endl;
cin>>nr;

funkcja(glowa,nr);
cout<<endl;

drukuj(glowa);

kasuj(glowa);
return 0;
}

You might also like