【发布时间】:2009-09-05 02:22:24
【问题描述】:
尝试通过遍历列表的循环来完成。
在循环中,我将头节点输入到我定义的排序函数中,然后我使用 strcmp 来确定节点中的哪个名称应该先出现。
它不起作用,因为写名字太早了。
我通过在列表中一次一个节点而不是回头查看第一个节点是否应该在最后一个节点之前来线性比较它们。解释的那部分会很有帮助。
现在对我来说最重要的两个函数定义如下: 我已经尽力去做我认为适合排序功能的事情。
void list::displayByName(ostream& out) const
{
list *ListPtr = NULL;
node *current_node = headByName;
winery *wine_t = new winery();
// winery is another class object type
// im allocating it to prevent a crash when I call it.
while ( current_node != NULL )
{
*(wine_t) = current_node->item;
wine_t = ListPtr->sort( current_node );
out << wine_t << endl;
current_node = current_node->nextByName;
}
delete wine_t;
}
winery * const list::sort( node * current_node ) const
{
// current_node is the first node.
const char *SecondName = NULL, *FirstName = NULL;
winery *wine_t = new winery();
if ( current_node != NULL )
{
SecondName = current_node->item.getName();
current_node = current_node->nextByName;
FirstName = current_node->item.getName();
}
if ( strcmp( FirstName, SecondName ) == -1 )
{
*(wine_t) = current_node->item;
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
else if ( strcmp( FirstName, SecondName ) == 1 )
{
*(wine_t) = current_node->item;
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
else return wine_t;// then the strings are equal
FirstName = NULL;
SecondName = NULL;
return wine_t;
}
我开始在这里开发我的节点:
void list::insert(const winery& winery)
{
node *current_node = new node( winery );
if ( headByName == NULL )
{
headByName = current_node;
headByRating = current_node;
tail = headByName;
current_node->prev = current_node;
}
else
{
current_node->prev = tail;
tail->nextByName = current_node;
}
tail = current_node;
current_node = NULL;
}
我认为它在上面的那个函数中是正确的。我可以在那里分类吗?
以下是我正在使用的变量:
public list
{
...
void insert(const winery& winery);
void displayByName(ostream& out) const;
}
private:
struct node
{
node(const winery& winery); // constructor
winery item;
node * prev;
node * nextByName;
node * nextByRating;
};
winery * const sort(node*) const;
node * headByName;
node * headByRating;
node * tail;
};
感谢任何帮助。 非常感谢 =)
【问题讨论】:
-
@lampshade,您可以更正原始问题以添加详细信息,而不是重复发布 stackoverflow.com/questions/1309960/linkedlist-part。
-
你到底怎么了?
-
我已经联系了 SO 团队。
标签: c++ sorting linked-list