Hi stackoverflow community!
I am trying to implement addAfter() method for my SinglyLinkedList and I thought I was doing it correctly, but nothing is printing out. Would love to see y'alls insight on what I might be missing:
public class LinkedList {
private EmployeeNode head;
private EmployeeNode tail;
private int size;
public void addAfter(EmployeeNode node, Employee newEmployee) {
EmployeeNode newNode = new EmployeeNode(newEmployee);
newNode.setNext(node.getNext());
node.setNext(newNode);
size++;
if(tail == null) {
tail = newNode;
}
}
}
*To keep the code brief, I have not added the other methods, but everything else works perfectly fine such as append(), addToFront(), removeFromEnd(), printList(), etc.
Main Method:
public class Main {
public static void main(String[] args) {
Employee janeSmith = new Employee("Jane", "Smith", 44);
Employee maryJames = new Employee("Mary", "James", 34);
Employee johnDoe = new Employee("John", "Doe", 78);
Employee andrewJackson = new Employee("Andrew", "Jackson", 24);
EmployeeNode node = new EmployeeNode(maryJames);
LinkedList list = new LinkedList();
list.addToFront(janeSmith);
list.addToFront(maryJames);
list.addToFront(johnDoe);
list.addAfter(node, andrewJackson);
list.printList();
}
**Employee Class just has firstName, lastName, and id instance variables as seen in the above instantiations.
EmployeeNode Class:
public class EmployeeNode {
private Employee employee;
private EmployeeNode next;
public EmployeeNode(Employee employee) {
this.employee = employee;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public EmployeeNode getNext() {
return next;
}
public void setNext(EmployeeNode next) {
this.next = next;
}
public String toString() {
return employee.toString();
}
}
When you say
You are creating a node that contains maryJames and has no value for next.
Than you say
You are creating an different EmployeeNode that contains maryJames. This EmployeeNode has the 'next' element set correctly (I assume) by the addFront(method).
When you say
You are using the EmployeeNode that does not have 'next' set. And the addAfter() method won't work correctly.
You need to use the instance of EmployeeNode is part of the LinkedList.