logo CodeStepByStep logo


Language/Type: C++ linked lists pointers

Write a function named isSortedBy that accepts two parameters, a pointer to a ListNode representing the front of a linked list, and an integer k, 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 variable named front points to the front of a list containing 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 isSortedBy(front, 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 isSortedBy(front, 2) should return true.

Notice that duplicates are allowed in the sub-lists. The call of isSortedBy(front, 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.


  • 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.

Assume that you are using the ListNode structure as defined below:

struct ListNode {
    int data;         // value stored in each node
    ListNode* next;   // pointer to next node in list (nullptr if none)
Function: Write a C++ function as described, not a complete program.

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.