In: Computer Science
After the code executes (in C++), what will the linked list 8->4->3->7->5 look like? (8 is the head)
1a)
Node* newNode = new Node(26);
newNode->next = head->next;
head = newNode;
1b)
Node* curNode = head;
for(int i=0; i<2; i++)
curNode = curNode->next;
Node* temp = curNode->next;
curNode->next = curNode->next ->next;
delete temp;
temp = nullptr;
Given Linked list:-
8->4->3->7->5
1a) Given Code:-
Node* newNode = new Node(26);
newNode->next = head->next;
head = newNode;
After execution of the above code, newNode is created with data field:- 26 and address field is assigned with the address of the second node(i.e the node having data value 4). After this, the address of the new node is assigned to head Node. So, indirectly the new node comes before the node having data value 4.
So, the final list is:-
8->26->4->3->7->5
1b) Given Code:-
Node* curNode = head;
for(int i=0; i<2; i++)
curNode = curNode->next;
Node* temp = curNode->next;
curNode->next = curNode->next ->next;
delete temp;
temp = nullptr;
In the above code, curNode is assigned with the address of head. Now the for loop will run twice and after execution of loop. The curNode is pointing to a node having data value 4.
After this, the temp will point to the node having data value 7. Now, the address field of curNode is assigned with the address of node having data value 7, and the temp is deleted. Due to this node having value 3 is deleted from the list.
So, the final list is:-
8->26->4->7->5