基本C ++链接列表节点&指针探针

时间:2014-02-28 03:01:09

标签: c++ pointers linked-list

我一直在尝试从链接列表中的第一个节点检索数据已经有一段时间了。原谅我,但我还是C ++的新手,特别是指针和链表。

以下是我从文本文件中读取数据的方法(到目前为止工作正常)

void readFile(ifstream& budgetFile, budgetItem *newNode, int& counter, budgetItem *temp, budgetItem *header)
{
char pauseChar;

int ctype;
string cname;
double camount;
char cleared;

itemPtr listTop = NULL;

while (!budgetFile.eof())
{

    //newNode = new budgetItem;

    budgetFile >> ctype >> cname >> camount >> cleared;

    newNode->theType = ctype;
    cout << newNode->theType << endl;
    //cout << ctype << endl;
    newNode->name = cname;
    cout << newNode->name << endl;
    newNode->amount = camount;
    cout << newNode->amount << endl;
    if (cleared == 'Y') {
        newNode->cleared = true;
    }
    else{
        newNode->cleared = false;
    }

    newNode->next = listTop;
    listTop = newNode;

    if (counter == 0)
    {
        header = newNode;
    }

    counter++;
}

return;
}

以下是我尝试从第一个节点开始检索数据的方法。它根本不起作用。任何有关这方面的帮助将不胜感激。

void showBudget (budgetItem *newNode, budgetItem *temp, budgetItem *header)
{
double incomeTotal;
double expenseTotal;
double differenceTotal;

//itemPtr *newlist;
//newNode = header;
itemPtr listTop;

budgetItem *here = listTop;

do {
    cout << "INCOME:" << endl;
    cout << "      Item              Amount       Cleared" << endl;
    cout << "      ----------------  -------      -------" << endl;
    if (newNode == NULL)
    {
        cout << "List is empty." << endl;
    }
    else
    {
        if (newNode->theType != 0)
        {
            cout << "       " << newNode->name << setw(23) << fixed << setprecision(2) << newNode->amount << "        ";
            if (newNode->cleared == true) {
                cout << "no" << endl;
            }
            else{
                cout << "yes" << endl;
            }
        }
        else{
            cout << endl;
        }
    }
    newNode = newNode->next;
} while (newNode != NULL);

cout << "End of List." << endl;

return;
}

1 个答案:

答案 0 :(得分:0)

    // ... 
    counter++;

    // create next node here:
    newNode = new budgetItem;
}

对于列表中的每个新元素,我们需要在内存中分配新对象。你一次又一次地使用同一个对象。