开发者

Why does not execute this linked list code? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I don't know why this code doesn't work...

#include <iostream>

using namespace std;

struct Triple {int row, col, value;};

class Matrix;

class MatrixNode 
{
friend class Matrix;
friend istream& operator>>(istream&, Matrix&);
private:
    MatrixNode *down, *right;
    bool head;
    union {
        MatrixNode *next;
        Triple triple;
    };
    MatrixNode(bool, Triple*);
};

MatrixNode::MatrixNode(bool b, Triple* t)
{
    head = b;
    if (b) {right = down = this;}
    else triple = *t;
}

class Matrix {
friend istream& operator>>(istream&, Matrix&);
public:
    ~Matrix();
private:
    MatrixNode *headnode;
};

istream& operator>>(istream& is, Matr开发者_开发知识库ix& matrix)
{
    Triple s;
    cout << "Enter the numbers of row, colume, value" << endl;
    is >> s.row >> s.col >> s.value;

    int p = max(s.row, s.col);

    matrix.headnode = new MatrixNode(false, &s);
    if (p == 0) { matrix.headnode->right = matrix.headnode; return is;}
    MatrixNode **head = new MatrixNode*[p];
    for (int i = 0; i < p; i++)
        head[i] = new MatrixNode(true, 0);
    int currentRow=0;
    MatrixNode *last = head[0];

    for (int i = 0; i < s.value; i++)
    {
        Triple t;
        cout << "Enter the terms" << endl;
        is >> t.row >> t.col >> t.value;
        if (t.row > currentRow){
            last -> right = head[currentRow];
            currentRow = t.row;
            last = head[currentRow];
        }
        last = last -> right = new MatrixNode(false, &t);
        head[t.col]->next = head[t.col]->next->down = last;
    }

    last -> right = head[currentRow];
    for (int i = 0; i < s.col; i++)
        head[i] -> next -> down = head[i];
    for(int i = 0; i < p - 1; i++)
        head[i] -> next = head[i+1];
    head[p-1] -> next = matrix.headnode;
    matrix.headnode -> right = head[0];
    delete [] head;
    return is;
}


int main()
{
    Matrix *a = new Matrix;
    Matrix *b = new Matrix;

    cin >> *a;
    cin >> *b;

}


The specific problem is that head[t.col]->next is uninitialized, and you're dereferencing it.

The more general problem is that you've bitten off more than you can chew. You are trying to build something well beyond your ability, and you're trying to do it in one step. Try building a much simpler linked list, say, one without the union, without the operator>>, and with only one dimension, not three. Once you are comfortable with that, work your way up to more advanced structures, in small steps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜