2. (20 pts) Examine the mystery method and hand simulate the call nystery(start)
ID: 3759078 • Letter: 2
Question
2. (20 pts) Examine the mystery method and hand simulate the call nystery(start): using the linked list below. Cross out ALL pointers that are replaced and Write in new pointers. You have a good amount of time to do the hand simulation, so work slowly and carefully and try to be neat. void mystery(LN* x) l class LN public: while (b->next != nullptr) { a->next->next - b->next; b->next - a->next; a>next = b; a=b; b = b>next . >next ; //constructors...not needed int value; LN* nexti startExplanation / Answer
Note that the function call is: mystery(start). Here start is the first node pointer in the linked list., that is start is pointing to the node with value 1.
LN *a = x; // Here x a pointer declared which is also pointing to the same node 1.
*b = x->next->next ; //Ofcourse b is also a pointer declared, and it is pointing to the 3rd node. Keep in mind that, x is a node with 2 parts in it. x->value, x->next. Here x->value is the value it can store in the node, and x->next is the pointer to the next node. So, when x is pointing to 1, x->next will point to the node 2. x->next->next can be interpreted as (x->next)->next = A node 2->next. Which means b is pointing to a node 3.
The loop goes here:
while(b->next != null)
{
a->next->next = b->next;
b->next = a->next;
a->next = b;
a = b;
b= b->next->next;
}
Before entering the loop, a is pointing to 1, and b is pointing to 3.
3->next is not NULL(It is 4). So, go into the loop.
{
a->next->next = b->next; // Now 2->next will point to 4.
b->next = a->next; // Now b->next will point to 2.
a->next = b; // Now a->next will point to 3.
a = b; //Now a will point to 3.
b= b->next->next; //Now b will point to 4.
}
This time the condition again satisfies, as b->next i.e., 4> next points to 5.
By the time you come out of the loop, a points to 3, and b points to 4.
{
a->next->next = b->next; // Now 2->next will point to 5.
b->next = a->next; // Now b->next will point to 2.
a->next = b; // Now a->next will point to 4.
a = b; //Now a will point to 4.
b= b->next->next; //Now b will point to 5.
}
This time the condition again fails, as b->next i.e., 5-> next points to NULL.
By the time you come out of the loop, a points to 4, and b points to 5.
Why a->next->next = b->next makes a->next->next points to not 4.
This step makes a->next->next point to 4, when you are running the loop for the first time.
The second time, it will point to 5.
If you still have further queries, you just revert to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.