我查看了其他帖子,但没有找到适合我的查询的很好的解决方案。我不想对链接列表进行实际排序,我想看看它是否已排序。我有一个 C++ 中的链表问题。我被要求编写一个给定链表定义的函数来查看它是否已排序。
实现函数 isSorted – 如果链表中的值按升序排序,则返回 true。 (链表由整数组成)。
给定以下结构:
struct ListNode
{
double value; // The value in this node
struct ListNode *next; // To point to the next node
};
示例数据:从 isSorted 返回
1 -> 3 -> 7 正确
4 -> 2 -> 7 错误
() True // 空列表。
3 真实
1-> 5 -> 7 -> 2 错误
我有这样的东西。
bool NumberList::isSorted() const
{
ListNode *nodePtr; // To move through the list
nodePtr = head;
while (nodePtr)
{
if(nodePtr->value <= nodePtr->value+1)
nodePtr = nodePtr->next;
else
return false;
return true;
}
}
我不确定我这样做是否正确,我需要帮助。
谢谢。
也许这会起作用......
bool NumberList::isSorted() const
{
ListNode *nodePtr;
nodePtr = head;
double d;
if (!nodePtr) return true; // Empty list
// Save value of current node
d = nodePtr->value;
// Point to next node
nodePtr = nodePtr->next;
while (nodePtr)
{
if(d > nodePtr->value) return false; // Not sorted
// Save value of current node
d = nodePtr->value;
// Point to next node
nodePtr = nodePtr->next;
}
return true;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)