0

这可能看起来有点模糊,所以真的很抱歉。我正在写入文件并将此单链表中的排序节点打印到控制台。不幸的是,在排序列表中,它会在前面打印和写入一个额外的 0,并在末尾删除一个值。这是代码:

void SLLIntStorage::Read(istream& r)
{
    char c[13];
    r >> c;
    r >> numberOfInts;

    head = new Node;
    head->next = NULL;
    tail = head;
    r >> head->data;

    for (int i = 0; i < numberOfInts; i++)
    {
        Node* newNode = new Node;
        r >> newNode->data;

        if(_sortRead)
        {
            if(newNode->data > tail->data)
            {
                tail->next = newNode;
                tail = newNode;
            }
            else if(head->data > newNode->data)
            {
                newNode->next = head;
                head = newNode;
            }
            else
            {
                current = head;

                while(current->next != NULL)
                {
                    if(current->next->data > newNode->data)
                    {
                        newNode->next = current->next;
                        current->next = newNode;
                        break;
                    }
                    else
                    {
                        current = current->next;
                    }
                }
            }
        }
        else
        {
            tail->next = newNode;
            tail = newNode;
        }
    }
    print();
}

void SLLIntStorage::Write(ostream& w)
{
    current = head;

    for(int i = 0; i < numberOfInts; i++)
    {
        w << current->data << endl;

        if (current->next != NULL)
            current = current->next;
    }
}
void SLLIntStorage::print()
{
    current = head;

    for(int i = 0; i < numberOfInts; i++)
    {
        cout << current->data << endl;
        //system("pause");
        if(current->next != NULL)
        {
            current = current->next;
        }
    }
}

文件样本: 0 0 1 2 2 3 ........ 9995 9996 9996 9998 //这里应该是另一个9998

4

1 回答 1

0

看来你读了一个条目太多了。您首先在-loopr >> head->data; 之前的行中读取了一个条目。for然后,您在 -loop 中阅读了额外的numberOfInts条目以for获取总共numberOfInts+1条目。

于 2011-05-02T13:58:26.897 回答