【发布时间】:2017-10-19 19:53:25
【问题描述】:
我需要帮助将数据从类节点插入到链表中。 List 是节点的容器。它们需要根据姓氏、名字和年龄进行排序。 (我已经有运算符函数来比较它们)我只是不确定如何使用指针来插入和排序它们。 下面是我的两个类定义,以及到目前为止我的插入函数。我还从以前的项目中提供了一个潜在的选择排序算法,可以用来处理这个问题。有人可以帮忙吗?
//类声明
class node;
class list
{
public:
void insert(string f, string l, int a);
int length();
private:
node *head;
int listlength;
};
class node
{
friend list;
public:
node(); // Null constructor
~node(); // Destructor
void put(ostream &out); // Put
bool operator == (const node &); // Equal
bool operator < (const node &); // Less than
private:
string first, last;
int age;
node *next;
};
//MAIN中如何调用insert
while (!infile.eof())
{
infile >> first >> last >> age;
// Process if okay
if (infile.good())
a.insert(first, last, age);
};
//插入函数
void list::insert(string f, string l, int a)
{
node *temp1, *temp2 = head;
temp1 = new node();
temp1->first = f;
temp1->last = l;
temp1->age = a;
temp1->next = NULL;
if (listlength == 0)
{
temp1->next = head;
}
else
while (temp2->next != NULL)
{
;
}
}
//潜在排序算法
void sort(person b[], int count)
{
int i = 0, j = 0, indexofsmallest = i;
person smallest = b[i];
for (i = 0; i < count; i++)
{
smallest = b[i];
indexofsmallest = i;
for (j = i+1; j < count; j++)
{
if (b[j] < smallest)
{
smallest = b[j];
indexofsmallest = j;
}
}
//cstdlib swap function
swap(b[i], b[indexofsmallest]);
}
}
【问题讨论】:
-
为什么要使用列表?为什么不使用 std::list?
-
无关:您已经避免了
while (!infile.eof())陷阱的一部分。干得好,但您需要向if (infile.good())添加一个 else 案例以清除错误并从流中删除不可解析的数据。如果不这样做,程序将永远不会到达文件末尾并永远循环。 -
在
list::insert中,如果您添加到while (temp2->next != NULL)并检查*temp2 < *temp1,您最有可能找到正确的插入点。
标签: c++ sorting pointers linked-list container-classes