插入 istream c++ 时对单链表进行排序
当谈到 C++ 时,我是世界上最基本的人,我想知道你们是否可以帮助我,是否可以。我试图对读入 istream 的节点进行排序,但是当它们被读入时。网络上的代码非常复杂,我想知道是否有一个非常基本的方法来实现这一点。
这是我的读取方法,到目前为止它读入了 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;
}
}
,这是我的头文件中的 Node 类
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
};
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
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看这是否能让你正确思考这个问题:
你从一副牌面朝上开始。你想要对这副牌进行排序,但你必须遵循一些奇怪的规则。
你放置未排序的牌,这样你只能看到最上面的牌。首先将第一张卡片移至已排序的卡片堆中(其中一张卡片会自动按排序顺序)。
查看下一张未分类的卡片。如果它比顶部排序的卡片更大(或更小,无论如何),则将顶部排序的卡片移动到第三堆。继续将卡片一张一张地移至第三堆,直到您的新卡片小于下一张已排序的卡片或已排序的卡片堆为空,然后将未排序的卡片移至已排序的卡片堆上。将第三堆牌一张一张地移回到已排序的牌堆中。
重复上一步,直到未排序的堆为空。
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.