What does the following Java code print? Draw a picture of the linked list after
ID: 3714617 • Letter: W
Question
What does the following Java code print? Draw a picture of the linked list after each step.
LinkedList<String> staff = new LinkedList<String> (); //Step 1
staff.addFirst("Harry"); //Step 2
staff.addLast("Diana"); //Step 3
staff.addFirst("Tom"); //Step 4
System.out.println(staff.removeLast()); //Step 5
System.out.println(removeFirst()); //Step 6
System.out.println(removeLast()); //Step 7
What does the following code print? Draw a picture of the linked list INCLUDING the iterator position after each step.
LinkedList<String> staff = new LinkedList<String> (); //Step 1
ListIterator<String> iterator = staff.listIterator(); //Step 2
iterator.add("Tom"); //Step 3
iterator.add("Diana"); //Step 4
iterator.add("Harry"); //Step 5
iterator = staff.listIterator(); //Step 6
if (iterator.next().equals("Tom"))
{iterator.remove();} //Step 7
while (iterator.hasNext())
{ System.out.println(iterator.next()); } //Step 8
Explanation / Answer
ANSWER :
In step 1 it is creating the object of linked list.
in step-2 adding an object Harry now linked list is :
Harry --->NULL
In step -3 adding Diana after step -3 the linked list is :
Harry---->Diana--->NULL
In step -4 adding the Tom after this linked list will be :
Harry--->Diana---->Tom-->NULL
In step 5 removing the last then after this step linked list will be:
Harry--->Diana---->NULL
In step 6 removing the first then linked list is :
Diana---->NULL
In step 7 removing the last after this since there is only one node in the linked list so it will destroyhte whole linked list.
ANSWER 2:
Step -1 creating the LinkedList <String > staff object here.
Step -2 here we are creating the object of ListIterator on staff linked list.
Step -3 in this step we are adding objectTom. Now linked List will be :
Tom--->NULL.
Step -4 adding Diana now linked list will be :
Tom--->Diana--->NULL
Step --5addding Harry now linked list is :
Tom--->Diana--->Harry--->NULL
step -6 creating the iterator object on staff linked list object.
step -7 In this step we are finding the element Tom and removing it andafter this linked list will be :
Diana--->Harry--->NULL
Step -8 In this step we are printing the linked list using iterator.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.