I looked at other posts and didnt find a great solution for my inquiry. I don't want to actually sort the linked list I want to see if its sorted or not. I have a linked list question in c++. I am asked to code a function given a linked list definition to see if its sorted.
Implement the function isSorted – it returns true if the values in the linked list are sorted in increasing order. (The linked list is composed of integers).
given the following sturct:
struct ListNode
{
double value; // The value in this node
struct ListNode *next; // To point to the next node
};
Sample data: Return from isSorted
1 -> 3 -> 7 True
4 -> 2 -> 7 False
() True // Empty List.
3 True
1-> 5 -> 7 -> 2 False
I have something like this.
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;
}
}
I'm not sure if i'm doing this right, I need help. Thank you.
Maybe this will work...
If the list is sorted in ascending order, then for the comparison function you're using each node has greater or equal value to the previous one. I.e. the values are never decreasing. Just iterate through the nodes and check that.
Note: the condition you have shown,
does not check anything reasonable: it checks whether a value is less than or equal to that value plus 1.
One idea for a more reasonable condition is to compare
nodePtr->value
to the previous node's value. To do that easily, you need to have stored the previous node's value (or a pointer to the previous node) in the previous iteration. In some variable.