0

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;
}
2
  • What error exactly you are getting? Commented Nov 25, 2014 at 5:32
  • Crash Unhandled exception at 0x013C5A78 in L3_P2.exe: 0xC0000005: Access violation reading location 0x00000000. Commented Nov 25, 2014 at 5:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also since he are calculating average data type of info should be float
@AshwaniDausodia May be.. but what will he get by adding and then by taking avg..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.