Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ lets say, I want to sort data using a function void sort(node, *head); how w

ID: 3857609 • Letter: C

Question

C++

lets say, I want to sort data using a function

void sort(node, *head);

how will I implement this? Please use the given function and do not add any other function or parameter to it. This is my 3rd time posting and looks like people are not reading the instruction. Do not answer if you do not understand what I want it to be. Pass it to next person. Again. I want a function that sort using given function not a function that you want.

Thanks!

#include<iostream>

using namespace std;

typedef struct node

{

int data; // will store information

node *next; // the reference to the next node

};

node *insert(node *current_head, int x);

void printList(node *head);

int frequency(node *head, int searchItem);

//void sort(node *head);

int main()

{

node *head = NULL; //empty linked list

for (int i = 1; i <= 3; i++)

{

head = insert(head, i*i);

}

for (int i = 1; i <= 3; i++)

{

head = insert(head, i*i);

}

printList(head);

cout << "Frequency of 9 in the list is " << frequency(head, 9) << endl;

cout << "Frequency of 12 in the list is " << frequency(head, 12) << endl;

//sort(head);

cout << "sort has been called! ";

//printList(head);

system("pause");

return 0;

}

node *insert(node *current_head, int x)

{

node* temp = new node;

temp->data = x;

temp->next = current_head;

return temp;

}

void printList(node *head)

{

node *temp1; // create a temporary node

temp1 = head; // transfer the address of 'head' to 'temp'

if (temp1 == NULL)

{

cout << endl << "The linked list is empty" << endl;

return;

}

else

{

cout << "Linked list: ";

while (temp1 != NULL)

{

cout << temp1->data << " "; // show the data in the linked list

temp1 = temp1->next; // tranfer the address of 'temp->next' to 'temp'

}

cout << endl;

}

}

int frequency(node *head, int searchItem) {

int count = 0;

bool found = false;

while (head != nullptr && searchItem != found)

{

if (head == nullptr)

return -1;

if (head->data == searchItem)

count++;

head = head->next;

}

return count;

}

Explanation / Answer

void sort(node *head){

int isSwap;

    node *ptr, *left = NULL;

int tempVariable;

    if (head == NULL)

        return;

    do

    {

        isSwap = 0;

        ptr = head;

        while (ptr->next != left)

        {

            if (ptr->data > ptr->next->data)

{

tempVariable = ptr->data;

ptr->data = ptr->next->data;

ptr->next->data = tempVariable;

isSwap = 1;

            }

            ptr = ptr->next;

        }

        left = ptr;

    }

    while (isSwap);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote