Я уже несколько часов работаю над своим методом добавления и, кажется, попал в блокпост. Мой метод должен искать каждый узел в списке, чтобы увидеть, есть ли соответствующий номер сотрудника, а если нет, добавьте объект в порядок номера сотрудника.Не удается добавить узлы в моем связанном списке (java)
К сожалению, я даже не могу добавить узел в начало или конец моего списка. Кажется, я понимаю логику. Мне нужно выполнить поиск в моем списке, чтобы найти, где я хочу узел, тогда все, что мне нужно сделать, это связать ссылку нового узла с уже существующей. Я думаю, что я либо неправильно создаю узлы, либо не свяжу их правильно. Каждый раз, когда я пытаюсь проверить свой код, в моем списке появляется только один узел.
import java.util.*;
public class HumanResources
{
private EmployeeNode first;
employee data = new employee();
private class EmployeeNode
{
//data members of employeenode
private EmployeeNode link;
employee data = new employee();
private EmployeeNode()
{
data = null;
link = null;
}
private EmployeeNode (employee emp)
{
data = emp;
link = null;
}
}
public EmployeeNode search (employee search)
{
EmployeeNode current = first;
if (first == null)
{ return null;}
while((present != null) && (present.data != search))
{
present = present.link;
}
return present;
}
private EmployeeNode nextInList(EmployeeNode x)
{
return x.link;
}
public boolean isEmpty()
{
return (first == null);
} // end of isEmpty()
public HumanResources()
{
first = null;
}
public HumanResources (employee x)
{
this.data = x;
}
public boolean addEmployee(employee emp)
{
EmployeeNode current = new EmployeeNode();
current = first;
if (current == null)
{
first = new EmployeeNode(emp);
return true;
}
else
{
while(current.link != null)
{
EmployeeNode temp = new EmployeeNode();
temp.data = emp;
temp.link = current;
}
return true;
}
}
public Employee findEmployee(String EmpNumber)
{
EmployeeNode current = first;
if(first == null)
{
return null;
}
else{
while (current != null)
{
public String toString()
{
EmployeeNode display;
display = first;
String temp = "";
while(display != null)
{
temp += display.data + "\n";
display = display.link;
}
return temp;
}
}
А вот мой сотрудник класса
import java.util.*;
/**
This class manipulate information relating to employees
*/
public class employee {
private String empNumber;
private String name;
private String department;
private double salary;
/**
Zero parameter constructor that sets the values to null
*/
public employee()
{
empNumber = null;
name = null;
department = null;
salary = 0.0;
}
/**
Four parameter constructor to initialize the data members to the give values
@param kempnumber Employee's ID number
@param kname Employee's name
@param kdepartment Employee's department name
@param ksalary Employee's salary
*/
public employee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
/**
copy constructor
*/
public employee (employee copy)
{
empNumber = copy.empNumber;
name = copy.name;
department = copy.department;
salary = copy.salary;
}
/**
Four parameter constructor to set data members to given value
@param kname Employee's name
@param kdepartment Employee's department name
@param ksalary Employee's salary
*/
public void setEmployee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary)
{
this.salary = salary;
}
public String toString()
{
return (empNumber + " " + name + " " + department + " " +salary);
}
public boolean equals(employee compareto) {
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if (firstemployee == secondemployee) {
return true;
}
else {
return false;
}
}
public int compareTo(employee compareto)
{
int less = -1;
int same = 0;
int more = 1;
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if(firstemployee > secondemployee)
{
return more;
}
else if(firstemployee == secondemployee)
{
return same;
}
else
{
return less;
}
}
}
'while (current.link! = Null) { EmployeeNode temp = new EmployeeNode(); temp.data = emp; temp.link = current; } '- что вы сейчас думаете об этом? – immibis
Цикл while проходит через весь список до конца. Temp - это узел, который я хочу вставить в список. И я думал, что temp.link = current будет тем, как я подключу временный узел к другому узлу в списке? – Alex
Почему, по-вашему, цикл while проходит через весь список до конца? То, что у вас есть, «в то время как у первого узла есть ссылка (т. Е. Список имеет длину не менее двух узлов), создавать новые узлы и ничего не делать с ними (поэтому они в конечном итоге собирают мусор)» – immibis