CSE 310 Recitation – 2
1. Given the following linked list and Node definition.
struct Node
{
int data;
Node* next;
}
1.1 [2 pts] As above shows, prv and current are pointers that is currently pointing to Node 17
and 5 respectively. Write segment of C++ code to insert a new Node with value 4 after
current node and update the two pointers prv and current accordingly (i.e. current should
point to Node 4 and prv should point to 5 instead).
Answer: (1.1)
First we need to create a new node then assign the value 4 to it. We then set its next pointer
to point to the node after current. After that we set its next pointer to point to the node
after the current. We then update the current->next to point to this new node and move prv
to point to current which is 5. Move the current to new inserted node 4.
The code looks like this:
struct Node
{
int data;
Node* next;
}
//Create the new node and assign the value 4
Node* newNode = new Node();
newNode->data = 4;
//Insert new node after the current node
newNode->next = current->next;
current->next = newNode;
//moving prv to point current
prv = current;
current = newNode;
Now prv points to the Node with value 5 and the current points to the new node with value
4.
1.2 [2 pts] Still as the original diagram shows, write segment of C++ code to delete Node 5
and update the two pointers prv and current accordingly (i.e. current should point to Node -
9 and prv should point to 17 instead).
Answer: (1.2)
prv->next = current->next; //linking previous node to the next node
Node* temp = current; //store the current node to delete it.
current = current->next; // current now points to Node -9
delete temp;
temp = nullptr;
1.3 [2 pts] Write segment of C++ code to compute sum of all integers stored inside above
linked list and save it inside a variable called sumInt.
Answer: (1.3)
Int sumInt = 0;
Node* current = head;
while (current != nullptr){
sumInt += current->data; // adding current node data to sumInt
current = current->next; // move to the next node
}
Answer 2: