4. A linked list of integers is shown below a. What is the output for the follow
ID: 3920285 • Letter: 4
Question
4. A linked list of integers is shown below a. What is the output for the following code in general? What should be added to the code to avoid a runtime error? Node p-firsti while (p.next != null) { pp.next; system.out.println (p.data) b. The output of the following code is the sum of all data values in the linked list. Explain the unintended side effect that occurs when this code is run. Rewrite the code to avoid this side effect int sum 0 while (first-null) sum first.data; first first.next; System.out.printin (s)Explanation / Answer
Question 4 (a):
Let's analyse the given code one by one-
Line 1: Node p=first;
This line intends to create a new instance of class First. However, this will lead to syntax error
as the syntactic structure is not correct. The correct syntax is:
Node p=new first();
Line 2: while(p.next!=null){
Line 3: p=p.next;
Line 4: }
The statement of while in Line 2 is a condition which will hold true as long as the next variable (pointer)
is not null. Line 3 simply update the pointer to the next element. Line 4 closes the while loop.
Thus, at the end of Line 4, the p node will point to the last element of the list.
Line 5: system.out.println(p.data)
This line prints the element present in the last node (pointed by p now).
Question 4 (b):
The above code will work absolutely fine except for two minor problems-
1) At the end of the while loop, the 'first' will now point to the last element which although is not wrong syntactically but 'first' pointing to the last element creates confusion to the user.
2) The last line should print sum instead of s.
Thus, the correct code is as follows:
int sum=0;
temp=first;
while(temp!=null) {
sum+=temp.data;
temp=temp.next;
}
system.out.println(sum)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.