Question: I'm trying to create a Doubly Linked List that allows for the addition and removal of new Nodes. During the addition (and removal) of Nodes,
I'm trying to create a Doubly Linked List that allows for the addition and removal of new Nodes. During the addition (and removal) of Nodes, it makes sure to sort the Node so that the Linked List will be in order when the values are printed out.
The Expected List should be: 92 91 91 90 80 79, but the Actual List is: 92 91 91 80 79 90
The Code is In Java, any help would be appreciated! I apologize for the formatting of the code
class DLLNode {
int score;
DLLNode prev;
DLLNode next;
DLLNode(int score) {
this.score = score;
}
}
class DoublyLinkedList {
DLLNode head;
int size = 0;
void add(int score) {
DLLNode newNode = new DLLNode(score);
if (head == null) {
head = newNode;
size++;
return;
}
DLLNode current = head;
while (current.next != null && score < current.score) {
current = current.next;
}
if (current == head && score >= current.score) {
newNode.next = head;
head.prev = newNode;
head = newNode;
size++;
} else if (current.next == null && score >= current.score) {
current.next = newNode;
newNode.prev = current;
size++;
} else {
newNode.next = current;
newNode.prev = current.prev;
(current.prev).next = newNode;
current.prev = newNode;
size++;
}
}
void remove(int score) {
if (head == null) {
return;
}
DLLNode current = head;
while (current != null && score != current.score) {
current = current.next;
}
if (current == null) {
return;
}
if (current == head) {
head = current.next;
}
if (current.prev != null) {
current.prev.next = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
}
size--;
}
public void printList() {
DLLNode current = head;
while (current != null) {
System.out.print(current.score + " ");
current = current.next;
}
System.out.println();
}
}
public class DLLOperator {
public static void main(String[] args) {
DoublyLinkedList DLLTest = new DoublyLinkedList();
DLLTest.add(90);
DLLTest.add(91);
DLLTest.add(92);
DLLTest.add(91);
DLLTest.add(80);
DLLTest.add(79);
//DLLTest.remove(90);
//DLLTest.add(52);
DLLTest.printList();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
