简体   繁体   English

插入 istream c++ 时对单链表进行排序

[英]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.当谈到 c++ 时,我是世界上最基本的人,我想知道你们是否可以帮助我,如果可以的话。 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.我试图对读入 istream 的节点进行排序,但因为它们被读入。web 上的代码非常复杂,我想知道是否有一种非常基本的方法来实现这一点。

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这是我的读取方法,到目前为止它读入 istream,这很棒,但现在我需要对其进行排序,因为它已读入。我的头疼哈哈

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这是我的 header 文件中的节点 class

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.重复上一步,直到未排序的堆为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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