16.6 Practice




Using the methods outlined in the “Benefits of LinkedLists” section, fill both a LinkedList and an ArrayList with 10,000 elements. Then, find the time it takes to access the last element of each list. Determine which type of list can access elements more efficiently. Hint: You can use the get(int position) method to access the element at a given position of a list.


Create a LinkedList of Strings, and ask the user to input 10 names one by one into the list. Names.java
  1. Output this list.
  1. Remove each name that has 5 or fewer letters, and output the new list.
  1. Add the word “Apple” to the beginning of the list.
  1. Add the word “Peanut” to the second-to-last position of the list. (Hint: Make sure to take advantage of LinkedList methods!)
  1. Output the new list.


Write a method which takes in a LinkedList of Strings and rearranges the elements (without creating a new list) so it is sorted in ascending order of String length. Don’t use any pre-existing sort methods… write your own. :)

Linkedlist - DIY

Implement a simple LinkedList
You will need to create a LinkedListNode class, which represents each item/node in the linked list:
  • Assume that the elements in the linked list are all of type int
  • Required functionality...
  • head(): get head of list
  • tail(): get tail of list
  • add(): add to tail of list
  • push(): push to head of list
  • pop(): remove head of list
  • toString(): return a String representation of the list

SinglyLinkedlist - DIY (Continued)

Adding an insert method to a SinglyLinkedList (details in SinglyLinkedList DIY section).
  1. Hint: It might be necessary to have a separate case for inserting at position 0, because that’s when you want to insert BEFORE the head. For all other positions (1, 2, etc.), you can simply traverse down the list, keeping track of the current node, and when you reach the position you want, add the node AFTER the current node.
  1. Alternatively, you can always add BEFORE the current node for all position cases (insert before the head to place the new node at pos 0, insert before node 1 to place the new node at pos 1, etc.), but then your exception case would be when the user wants to insert a node at the very end of the list. In this case, you’d have to write separate code to insert AFTER the last node. The following code should output “{2, 3, 4, 7}”. Make sure you have a toString() method defined!
The following code should output “{2, 3, 4, 7}”. Make sure you have a toString() method defined!
notion image
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.