czy ktoś wie czym rożni się zapis:
struct node
{
int x;
node *next;
};
od:
struct node
{
int x;
struct node *next;
};
czy ktoś wie czym rożni się zapis:
struct node
{
int x;
node *next;
};
od:
struct node
{
int x;
struct node *next;
};
Niczym, oznacza dokładnie to samo.
ok dzięki, jeszcze jedno pytanie dlaczego funkcja sum zawsze zwraca mi 0?
int main()
{
node* n1 = new node();
node* n2 = new node();
node* n3 = new node();
node* n4 = new node();
n1->x = 10;
n1->next=n2;
n2->x = 20;
n2->next=n3;
n3->x = 30;
n3->next=n4;
n4->x = 40;
n1->next=0;
cout<<sum(n1);
return 0;
}
long long int sum(node* n)
{
node* tmp = n;
long long int sum = 0;
while(tmp->next)
{
sum+=tmp->x;
tmp=tmp->next;
}
return sum;
}
n1->next=0;
ustawiasz wskaźnik na następny za pierwszym elementem na nullptr
. Czyli n1
jest ostatnim elementem listy.
A tutaj wyłącznie dodajesz element do sumy jeśli nie jest on ostatnim elementem:
while(tmp->next)
{
sum+=tmp->x;
tmp=tmp->next;
}
ok dzięki za pomoc.
temat do zamknięcia.