I need to enurse this method maintains natural ascending order. Any Ideas? \'fro
ID: 3681981 • Letter: I
Question
I need to enurse this method maintains natural ascending order. Any Ideas? 'front' and 'rear' are declared as null in the fields. Java is the language.
* Ensures the collection contains the specified element. Neither duplicate
* nor null values are allowed. This method ensures that the elements in the
* linked list are maintained in ascending natural order.
*
* @param element The element whose presence is to be ensured.
* @return true if collection is changed, false otherwise.
*/
public boolean add(T element) {
if (element == null) {
throw new NoSuchElementException();
}
// Checks for duplicates.
if (contains(element)) {
return false;
}
// Adds at position one of LinkedSet is empty.
if (size == 0) {
front = new Node(element);
rear = front;
}
// Adds to end of LinkedSet.
else {
rear.next = new Node(element);
rear.next.prev = rear;
rear = rear.next;
}
size++;
return true;
}
Explanation / Answer
Hi I have completed add method. In case of any issue please post whole program so that i can test it.
public boolean add(T element) {
if (element == null) {
throw new NoSuchElementException();
}
// Checks for duplicates.
if (contains(element)) {
return false;
}
Node temp = new Node(element);
// Adds at position one of LinkedSet is empty.
if (size == 0) {
front = temp;
rear = front;
}
// Adds to end of LinkedSet.
else if(element >= rear.data) {
rear.next = temp;
rear.next.prev = rear;
rear = rear.next;
}
// Add at begining of list
else if(element <= front.data){
temp.next = front;
fron.prev = temp;
front = temp;
}else{
Node curr = front;
while(element < curr.data){
curr = curr.next;
}
temp.next = curr.next;
curr.next.prev = temp;
curr.next = temp;
temp.prev = curr;
}
size++;
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.