Home » Programming & Data Structure » Programming and data structure miscellaneous » Question

Programming and data structure miscellaneous

Programming & Data Structure

  1. The following C function takes a simply-linked list as input argument. It modifies the list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank.
    type def struct node {
        int value;
       struct node *next;
    }    Node*;
    Node *move_to_front (Node *head) {
       Node *p, *q;
    if (head = = NULL | | (head -> next = = NULL)) return head;
       q = NULL; p = head;
       while (p - > next! = NULL)   {
       q = p;
       p = p - > next;
    }
    return head;
    }
    Choose the correct alternative to replace the blank line.
    1. q = NULL; p - > next = head; head = p;
    2. q - > next = NULL; head = p; p - > next = head;
    3. head = p; p -> next = q; q -> next = NULL;
    4. q-> next = NULL; p-> next = head; head = p;
Correct Option: D

When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop.
(i) Set next of q as NULL (q->next = NULL).
(ii) Set next of p as head (p->next = head).
(iii) Make head as p (head = p)
Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list.



Your comments will be displayed only after manual approval.