Reputation: 113
I want to create a linked list with integeres and between each two nodes I want to create another node that is the average between the one before and the one after.
In my add function I don't understand why my p pointer is at the last element in the linked list and not at the first. (this is why I think it crashes).
Thank you.
#include<iostream>
using namespace std;
struct Nod{
int info;
Nod* urm;
};
void create(const int &a, Nod *&p, Nod *&u)
{
if (p == NULL)
{
p = new Nod;
p->info = a;
u = p;
}
else
{
Nod *q;
q = new Nod;
q->info = a;
u->urm = q;
u = q;
}
u->urm = NULL;
}
void print(Nod *p)
{
while (p->urm)
{
cout << p->info<<" -> ";
p = p->urm;
}
cout << p->info;
}
void add(Nod *p)
{
while (p)
{
Nod *q;
q = new Nod;
q->info = (p->info + p->urm->info) / 2;
q->urm = p->urm;
p->urm = q;
p = p->urm->urm;
}
}
int main()
{
Nod *p, *u;
p = u = NULL;
char *numar;
numar = new char[100];
cout << "Enter a number: "; cin >> numar;
for (int i = 0; (unsigned)i <= strlen(numar) - 1; i++)
create(numar[i] - '0', p, u);
add(p);
print(p);
system("Pause");
return 0;
}
Upvotes: 0
Views: 85
Reputation: 9841
You need to add,
if(p->urm!=0)// this line
q->info = (p->info + p->urm->info) / 2;
Because p->urm could be NULL
.
I tried in Visual Studio after adding suggested line, and it is working fine. Though I do not understand what will you get by adding two addresses.
Upvotes: 1