简体   繁体   中英

Writing and Printing an extra 0 to sorted files and cutting node (singly linked list)off the end C++

That may seem kind of vague so really sorry. I am writing to a file and printing to a console the sorted nodes in this singly linked list. Unfortunately, in the sort list, it both prints and writes an extra 0 at the front and cuts a value off the end. Here is the code:

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;
        }
    }
}

File sample: 0 0 1 2 2 3........ 9995 9996 9996 9998 //supposed to be another 9998 here

It seems you read one entry too much. You first read an entry in the line r >> head->data; just before the for -loop. Then you read an additional numberOfInts entries in the for -loop for a total of numberOfInts+1 entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM