I have to convert my ArrayList code to Linked list without using import.java.util.LinkedList.
My previous code has 4 ArrayList (name, price, quantity, priority)
I have to sort arraylist depends on ArrayList prioirty.
So I did like this.
public void sortPriority() {
for (int i=0; i<name.length(); i++) {
for (int j=0; j<priority.size()-i-1; j++) {
if (priority.get(j).compareTo(priority.get(j+1)) > 0) {
int temp1 = priority.get(j);
priority.set(j,priority.get(j+1));
priority.set(j+1, temp1);
String temp2 = name.get(j);
name.set(j,name.get(j+1));
name.set(j+1, temp2);
double temp3 = price.get(j);
price.set(j,price.get(j+1));
price.set(j+1, temp3);
int temp4 = quantity.get(j);
quantity.set(j,quantity.get(j+1));
quantity.set(j+1, temp4);
}
}
}
}
I changed my name ArrayList to Linked List.
Since I cannot import java.util.LinkedList, I put my own code in other class called StringLinkedList.
abstract class StringLinkedList implements LinkList {
private ListNode head;
public StringLinkedList() {
head = null;
}
public void showList() {
ListNode position = head;
while (position != null) {
System.out.println(position.getData());
position = position.getLink();
}
}
public int length() {
int count = 0;
ListNode position = head;
while (position != null) {
count++;
position = position.getLink();
}
return count;
}
public void addNodeToStart(String addData) {
head = new ListNode(addData, head);
}
public void deleteHeadNode() {
if (head != null) {
head = head.getLink();
} else {
System.out.println("Deleting from an empty list.");
System.exit(0);
}
}
public boolean onList(String target) {
return find(target) != null;
}
private ListNode find(String target) {
boolean found = false;
ListNode position = head;
while ((position != null) && !found) {
String dataAtPosition = position.getData();
if (dataAtPosition.equals(target)) {
found = true;
} else {
position = position.getLink();
}
}
return position;
}
public String get(int i) {
assert (i>=0);
ListNode current = this.head;
while (i > 0) {
i--;
current = current.link;
if (current == null) {
return null;
}
}
return current.data;
}
public String set (int index, String element) {
ListNode current = this.head;
ListNode e = current;
String oldVal = e.element;
e.element = element;
return oldVal;
}
}
Every other methods works fine besides my set().
What should I change?
Your set() method ignores the index parameter that is passed in. As written it just modifies the item at the head of the list.
You will have to implement set() similarily to get() - find the item with the specified index, then set that item's element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With