Implement the methods removeFirst and addMiddle for a class that represents a do
ID: 672483 • Letter: I
Question
Implement the methods removeFirst and addMiddle for a class that represents a doubly linkedlist (all in Java). In this question both header and a tail are used. You may assume an appropriate declared nested class Node, and the use of a Head pointer. You may assume that the list does not store null values.
-check for special cases(empty list)
-any aditional pointers or iterators must be explicity declared.
-The method must return the either a pointer to the deleted node(removeFirst) or an indication of succes(addMidle).
ALL IN JAVA.
Explanation / Answer
import java.io.*;
import java.util.*;
class Node{
int val;
Node next;
Node prev;
public Node(int n){
val = n;
next = null;
prev = null;
}
public Node(){
next = null;
prev = null;
}
}
class linklist{
Node head;
Node tail;
public linklist(){
head = new Node();
tail = new Node();
head = tail;
}
void insert(int n){
Node temp = new Node(n);
if (head == tail){
head = temp;
head.next = tail;
tail.prev = head;
tail = temp;
}
else{
temp.next = head;
head = temp;
}
}
Node removeFirst{
if (head != null){
Node temp = head;
head = head.next;
return temp;
}
else{
System.out.println("List is empty");
return null;
}
}
void addMiddle(int n){
if (head == tail){
Node temp = head;
head = head.next;
return;
}
Node slow = head;
Node fast = head;
while (fast != tail && fast != null){
slow = slow.next;
fast = fast.next.next;
}
Node temp = new Node(n);
temp.prev = slow.prev;
temp.next = slow;
slow.prev = temp;
}
}