InterviewSolution
| 1. |
How To Insert A Node In Random Location In The List? |
|
Answer» As above, you’d initial produce the new node. Currently if the position is one or the list is empty, you’d insert it initially position. Otherwise, you’d traverse the list until either you reach the specified position or the list ends. Then you’d insert this new node. Inserting within the middle is that the difficult case as you have got to make sure you do the POINTER assignment within the correct order. First, you’d set the new nodes next pointer to the node before that the new node is being inserted. Then you’d set the node to the position to purpose to the new node. REVIEW the code below to GET an idea. VOID InsertNode(int data, int position) { /* 1. create the new node */ Node *temp = new Node; temp->data = data; temp->next = NULL; /* check if the position to insert is first or the list is empty */ if ((position == 1) || (head == NULL)) { // set the new node to point to head // as the list may not be empty temp->next = head; // point head to the first node now head = temp; return; } else { /* 2. traverse to the desired position */ Node *t = head; int currPos = 2; while ((currPos < position) && (t->next != NULL)) { t = t->next; currPos++; } /* 3. now we are at the desired location */ /* 4 first set the pointer for the new node */ temp->next = t->next; /* 5 now set the previous node pointer */ t->next = temp; } } As above, you’d initial produce the new node. Currently if the position is one or the list is empty, you’d insert it initially position. Otherwise, you’d traverse the list until either you reach the specified position or the list ends. Then you’d insert this new node. Inserting within the middle is that the difficult case as you have got to make sure you do the pointer assignment within the correct order. First, you’d set the new nodes next pointer to the node before that the new node is being inserted. Then you’d set the node to the position to purpose to the new node. Review the code below to get an idea. void InsertNode(int data, int position) { /* 1. create the new node */ Node *temp = new Node; temp->data = data; temp->next = NULL; /* check if the position to insert is first or the list is empty */ if ((position == 1) || (head == NULL)) { // set the new node to point to head // as the list may not be empty temp->next = head; // point head to the first node now head = temp; return; } else { /* 2. traverse to the desired position */ Node *t = head; int currPos = 2; while ((currPos < position) && (t->next != NULL)) { t = t->next; currPos++; } /* 3. now we are at the desired location */ /* 4 first set the pointer for the new node */ temp->next = t->next; /* 5 now set the previous node pointer */ t->next = temp; } } |
|