Question: Q) To class SinglyLinkedList, add method insertInMiddle(E e) that inserts a new node in the middle of the list ( list should have at least

Q) To class SinglyLinkedList, add method insertInMiddle(E e) that inserts a new node in the middle of the list ( list should have at least two nodes initially, if not just display an error message) if the list has odd number of nodes, insert after the one in the middle.

(Here is the code) please solve it corectly

thanks

-------------------------------------------------------------

public class SinglyLinkedList { private Node head = null; private Node tail = null; private int size = 0;

public SinglyLinkedList() { }

public int size() { return size; }

public boolean isEmpty() { return size == 0; }

public E first() { if (isEmpty()) return null; return head.getData(); }

public E last() { if (isEmpty()) return null; return head.getData(); }

public void addFirst(E e) { head = new Node<>(e, head); if (size == 0) tail = head; size++;

}

public void addLast(E e) { Node newest = new Node<>(e, null); if (isEmpty()) head = newest; else tail.setNext(newest);

tail = newest; size++; }

public E removeFirst() { if (isEmpty()) return null; E answer = head.getData(); head = head.getNext(); size--; if (size == 0) tail = null; return answer; }

public E removeLast() { if (isEmpty()) return null; E answer = tail.getData(); if (head == tail) head = tail = null; else { Node tmp = head; while (tmp.getNext() != tail) tmp = tmp.getNext(); tmp.setNext(null); tail = tmp; } size--; return answer; }

public void display() { for (Node tmp = head; tmp != null; tmp = tmp.getNext()) System.out.println(tmp.getData()); } } //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public class Node { private E data; private Node next;

public Node(E d, Node n) { data = d; next = n; }

public E getData() { return data; }

public Node getNext() { return next; }

public void setNext(Node n) { next = n; }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!