嗨,stackoverflow社区!
我正在尝试为我的SinglyLinkedList实现addAfter((方法,我认为我做得很正确,但没有打印出任何内容。很想看到你们对我可能错过的东西的见解:
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;
}
}
}
*为了简洁起见,我没有添加其他方法,但其他方法都很好,如append((、addToFront((、removeFromEnd((、printList((等。
主要方法:
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类只有firstName、lastName和id实例变量,如上面的实例所示。
EmployeeNode类:
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();
}
}
当你说时
EmployeeNode node=新的EmployeeNode(maryJames(;
您正在创建一个包含maryJames的节点,该节点没有下一个的值。
比你说的
addToFront(maryJames(
您正在创建一个包含maryJames的不同的EmployeeNode。这个EmployeeNode通过addFront(方法(正确设置了"next"元素(我认为(。
当你说
list.addAfter(node,andrewJackson(;
您使用的EmployeeNode没有设置"next"。addAfter((方法无法正常工作。
您需要使用EmployeeNode的实例,它是LinkedList的一部分。