logo CodeStepByStep logo

partitionSort

Language/Type: C++ linked lists pointers

Write a function named partitionSort that accepts as a parameter a reference to a pointer to the front of a linked list. Your function should assume that the linked list's elements are already sorted by absolute value, and rearrange the list into sorted order. Suppose a variable named front points to the front of a list that stores the values below. Notice that the values are in order of absolute value; that is, they would be in sorted order if you ignored the sign of each value. The call of partitionSort(front); should reorder the values into sorted, non-decreasing order (including sign).

{0, 0, -3, 3, -5, 7, -9, -10, 10, -11, -11, 11, -11, 12, -15}    list before call

                                                                 list after call of
{-15, -11, -11, -11, -10, -9, -5, -3, 0, 0, 3, 7, 10, 11, 12}    partitionSort(front);

Because the list is sorted by absolute value, you can solve this problem very efficiently. Your solution is required to run in O(N) time where N is the length of the list. If the list is empty or contains only one element, it should be unchanged by a call to your function. The behavior of your function is undefined if the initial list is not already sorted by absolute value; you do not need to handle that case.

Constraints: Do not modify the data field of existing nodes. Do not create any new nodes by calling new ListNode(...). You may create as many ListNode* pointers as you like, though. Do not use any auxiliary data structures such as arrays, vectors, queues, maps, sets, strings, etc. Do not leak memory. Your code must run in no worse than O(N) time, where N is the length of the list. Your code must solve the problem by making only a single traversal over the list, not multiple passes.

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.