logo CodeStepByStep logo

isSortedBy

Language/Type: C++ linked lists pointers

Write a member function named isSortedBy that could be added to the LinkedIntList class. The function accepts an integer k as a parameter and that returns true if the list of integers is sorted in non-decreasing order when examined "by k" and false otherwise. When examining a list "by k," you pick any element of the list and consider the sublist formed by that element followed by the element that comes k later, followed by the element that comes 2k later, followed by the element that comes 3k later, and so on. For example, suppose that a LinkedIntList variable named list stores the following sequence of numbers:

{1, 3, 2, 5, 8, 6, 12, 7, 20}

This list would normally not be considered to be sorted, which means the call of list.isSortedBy(1) should return false. But when examining elements by 2, we get two sorted sub-lists: {1, 2, 8, 12, 20} and {3, 5, 6, 7}. So the call of list.isSortedBy(2) should return true.

Notice that duplicates are allowed in the sub-lists. The call of list.isSortedBy(3) returns false because one of the resulting sub-lists is not sorted:

{1, 5, 12} (sorted), {3, 8, 7} (NOT sorted), and {2, 6, 20} (sorted)

By definition, an empty list and a list of one element are considered to be sorted. The function should return true whenever k is greater than or equal to the length of the list, because in that case all of the resulting sub-lists would be of length 1. Your function should throw an integer exception if passed a k value that is less than or equal to 0.

Constraints:

  • Do not call any member functions of the linked list class to solve this problem. (Note: the list does not have a size or mysize data field.)
  • Do not use any auxiliary data structures such as arrays, vectors, queues, strings, maps, sets, etc.
  • Do not modify the data field of any nodes; you must solve the problem by changing the links between nodes.
  • You may not construct new ListNode objects, though you may create as many ListNode* pointers as you like.

Write the member function as it would appear in LinkedIntList.cpp. You do not need to declare the function header that would appear in LinkedIntList.h. Assume that you are adding this method to the LinkedIntList class as defined below:

class LinkedIntList {
private:
    ListNode* front;   // nullptr for an empty list
    ...
};

struct ListNode {
    int data;
    ListNode* next;
};
Member function: Write a member function that will become part of an existing class. You do not need to write the complete class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.