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

I need help implementing theses functions in c++ void moveElemToFront(int k) //

ID: 3545290 • Letter: I

Question

I need help implementing theses functions in c++

void moveElemToFront(int k) // Precondition: k is an integer. // The list might be empty or it might be non-empty // Postcondition: the kth element in the unordered linked list has moved to // the front of the list. Note that if the list contains less than k elements, // the list says unchanged. // You CANNOT call insertFirst() and deleteNode() functions in the implementation // of moveElemToFront(). bool allEqual(const node *head_ptr, TYPE val) // Precondition: head_ptr is the head pointer of a linked list. // TYPE is the template type of the class. // The list might be empty or it might be non-empty. // Postcondition: The return value is true if every node in the // list contains val in the data part. NOTE: If the list is empty, // then the function returns true.

Explanation / Answer

These are the required functions for the given operations.

The structure used for the linklist is also mentioned.

struct linklist
{
    TYPE value;
    struct linklist *next;
    struct linklist *prev;
}node;


void moveElemToFront(const node *head_ptr, int k)
{
    if(head_ptr == NULL))
    {return;}
    else
    {
        int i;
        node *currentNode = head;
       
        for(i=1;i<k;i++)
        {
            if(currentNode == NULL)
            {return;}
            currentNode = currentNode->next;
        }
       
        TYPE kvalue = currentNode->value;
       
        while(currentNode->prev != NULL)
        {
            currentNode->value = currentNode->prev->value;
            currentNode= currentNode->prev;
        }
        currentNode->value = kvalue;
    }
}

bool allEqual(const node *head_ptr, TYPE val)
{
    if(head_ptr == NULL)   
    {return true;}
    else
    {
        node *currentNode = head;
       
        while(currentNode != NULL)
        {
            if(currentNode->value != val)
            {return false;}
            currentNode = currentNode->next;
        }
       
        return true;
    }
}


If you have any doubts reagrding the working, just leave a comment and I will try to help.
Have Fun!

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