To be done in Java LINKED LISTS Write two classes 1. The first class should have
ID: 3871146 • Letter: T
Question
To be done in Java LINKED LISTS Write two classes 1. The first class should have a method that removes a node at index (Singly Linked List) 2. The second class should have a method that adds a node at index (Doubly Linked List)No recursion Use tail for last node pointer if possible To be done in Java LINKED LISTS Write two classes 1. The first class should have a method that removes a node at index (Singly Linked List) 2. The second class should have a method that adds a node at index (Doubly Linked List)
No recursion Use tail for last node pointer if possible LINKED LISTS Write two classes 1. The first class should have a method that removes a node at index (Singly Linked List) 2. The second class should have a method that adds a node at index (Doubly Linked List)
No recursion Use tail for last node pointer if possible
Explanation / Answer
public class SinglyLinkedList {
…
public void removeFirst() {
if (head == null)
return;
else {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
}
}
}
public void removeLast() {
if (tail == null)
return;
else {
if (head == tail) {
head = null;
tail = null;
} else {
SinglyLinkedListNode previousToTail = head;
while (previousToTail.next != tail)
previousToTail = previousToTail.next;
tail = previousToTail;
tail.next = null;
}
}
}
public void removeNext(SinglyLinkedListNode previous) {
if (previous == null)
removeFirst();
else if (previous.next == tail) {
tail = previous;
tail.next = null;
} else if (previous == tail)
return;
else {
previous.next = previous.next.next;
}
}
}
2
begin insertAtFront(data):
if head is null:
head = new Node(data);
tail = null;
else:
if tail is null:
tail = new Node(data);
head.setNext(tail)
tail.setPrev(head)
else:
Node<T> prevHead = head;
Node<T> newHead = new Node(data);
newHead.setNext(prevHead)
prevHead.setPrev(newHead)
head = newHead
begin insertAtBack(T dataToInsert):
if head is null:
nodeToInsert = new Node(dataToInsert)
head = nodeToInsert
tail = null
else:
if tail is null:
tail = new Node(dataToInsert)
head.setNext(this.tail)
tail.setPrev(this.head)
else:
prevTail = tail
newTail = new Node(dataToInsert)
newTail.setPrev(prevTail)
prevTail.setNext(newTail)
tail = newTail
end if else;
end if else;
increment size
end insertAtBack;
begin removeNode(nodeToRemove):
prevNode = nodeToRemove.prev
nextNode = nodeToRemove.next
if prevNode is null:
head = null
head = nextNode
head.prev = null
else if nextNode is null:
tail = null
tail = prevNode
tail.next = null
else:
nodeToRemove = null
prevNode.next = nextNode
nextNode.prev = prevNode
end if else statement;
decrement size
end removeNode;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.