Implement a linked list in Java. Write a method insert that inserts integers in
ID: 3648131 • Letter: I
Question
Implement a linked list in Java. Write a method insert that inserts integers in ascending order in your linked list. Also, write a method that searches through the linked list and returns whether or not a specific number exists in the list. Demonstrate that your program works correctly by inserting elements out of order and printing out the elements in the order that they appear. Allow duplicate entries of the same number.hint: you need LinkedList.java, Node.java, Test.java
Clarification:
"out of order" in this case means that during the testing the insert
method has to be called with arguments (numbers) in no apparent order. For
example, here are "out of order" inserts
list.insert(7);
list.insert(3);
list.insert(10);
list.insert(5);
list.insert(10);
etc
The insert method has to keep the list in ascending order. But the testing method had to call the insert method "out of order" as described above.
Explanation / Answer
public class List { private ListNode head; //constructor public List() { head = null; } //to append the list public void appendItem(int item) { ListNode newNode = new ListNode(item); if (head == null) { head = newNode; } else { // find last item in list ListNode nextNode = head; while (nextNode.getNext() != null) { nextNode = nextNode.getNext(); } nextNode.setNext(newNode); } } public void insertItem(int item) { ListNode temp = new ListNode(item); ListNode current = head; for(int i = 1; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.