1) Write a sequence of C++ statements to add a node to the front [1] of the list. Make sure you put 4 in the new Node.
2) Write a while loop here that goes through the list until P points to the node right before the rear node. [2]
P = Front; // to start with
3) Write a for loop here that makes P stop at the (J-1)th node. [2] Think how many times the pointer needs to move.
P = Front; // to start with
1. Let,
front is the pointer pointing to the first node (front) of the list.
A Node class has two fields namely data (which contains the data/value ) and next (which is a pointer to the next node).
Node * temp = NULL;
Node temp = new Node()
temp->data= 4
temp->next = front
front = temp
2. P = front;
while (p->next->next != NULL){ //p->next->next always lloks at the next value of one node after the current one
p = p->next;
}
3. Suppose j = 4. We want pointer P to point to j-1 i.e 3rd node in the list. Initially P is already pointing to the first (front node). To come to 3rd node, we have to move P two times. On first move, P comes to 2nd node, on second move it comes to 3rd node. So , in general, the loop has to execute j-2 times.
P = front;
for(int i=1; i<=j-2; i++) {
p = p->next;
}
Please do let me know if you have any questions/doubts.
Get Answers For Free
Most questions answered within 1 hours.