简体   繁体   中英

Sort singly linked list on when inserting into istream c++

Im the most basic person in the world when it comes to c++ and I was wondering if you guys could help me out if that would be ok. Im trying to do sorting on nodes read into an istream but AS they are read in. The code on the web is very complex and I was wondering if there was a very basic way to acheive this.

Here is my Read Method and so far it reads into the istream which is great but now I need to sort it as its read in. My head hurts haha

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

    Node *node = new Node();
    head = node;

    for(int i = 0; i < numberOfInts; i++)
    {
        r >> node->data;
        cout << node->data << endl;
        node->next = new Node;
        node = node->next;
    }

}

and here is my Node class in my header file

class Node
{
public:
    Node() {} //default constructor
    Node(int d, Node* q = 0) : data(d), next(q) {} //constructor with parameters data and next
    int data; //holds data in node
    Node* next;//pointer to next node
};

See if this gets you thinking properly about the problem:

You start with a deck of cards face up. You want to sort the deck of cards but you have to follow some strange rules.

You place the unsorted deck of cards so that you can only see the top card. Start by moving the first card to your sorted pile (one card is automatically in sorted order).

Look at the next unsorted card. If it is bigger (or smaller, whatever) than the top sorted card then move the top sorted card to a third pile. Continue moving cards one by one to the third pile until your new card is smaller than the next sorted card or the sorted pile is empty, then move the unsorted card onto the sorted pile. Move the cards one-by-one back from the third pile to the sorted pile.

Repeat previous step until the unsorted pile is empty.

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