我得到了一个序列(单链表):
class Sequence
{
struct Node {
Key key;
Info info;
Node *next;
};
Node *head = NULL;
以及它的功能:
template <typename Key, typename Info>
Key Sequence<Key, Info>::getKey(int pos)const
{
Node *curr = head;
int i = 1;
while((curr) && (i < pos))
{
i++;
curr = curr->next;
}
if(curr)
{
return curr->key;
}
cout << "no Node with such a key" << endl;
return NULL;
}
它应该根据给定的参数POS得到一个密钥,它是列表中的位置。当它完美地适用于列表的范围时,它不适用于负值(它应该显示该节点不存在的一些文本)和超出范围的值(与负数相同的情况)。哪里出错?
跟踪Sequence
对象内列表的大小。这允许您在其他任何事情之前进行检查:
template <typename Key, typename Info>
Key Sequence<Key, Info>::getKey(int pos)const
{
//Add a size() member function to sequence that returns the size
// Store the size as a member variable
if(pos >= size() || pos < 0) {
cout << "no Node with such a key" << endl;
return NULL;
}
Node *curr = head;
int i = 1;
while((curr) && (i < pos))
{
i++;
curr = curr->next;
}
if(curr)
{
return curr->key;
}
return NULL;
}