Reputation: 47
I have an assignment for Java from class. It is about Employees, so there are three classes, Employee, EmployeeList and Nodes. I am required to make a double linked list out of this. The linked list is a custom class made by us, not the Java Provided one.
Now I am stuck in the add(Employee e) method. the method inputs parameters an Employee object and is required to be added to the end of the list.
this is the code
public void add(Employee emp) {
Node n = new Node(emp, null , null);
if(isEmpty() == true) {
setHead(n);
setTail(n);
n.setPrevious(null);
n.setNext(n);
}else {
Node c = getTail();
c.setNext(n);
n.setPrevious(c);
setTail(n);
}
}
in simple words, when the list is empty the method adds the Employee to the Node flawlessly, even when I add a second Employee to the list, its fine; but when I add anymore, and i try and retrieve it, I end up with incorrect results.
basically, if the list is populated, then Node c is assigned the tail of the List. "The tail or c" next was null, but now is Node n. Node n, since is next element after the tail, Node n's previous link is Node c, and tail is updated to Node n.
What am i doing wrong in here? if i try
list.getHead().getNext().getNext().getPrevious().getEmployee().getName());
where list = [a,b,c]; result is c, where it should be b.
that is;
head = a, a.getNext().getNext() == c;
c.getPrevious() == b;
but I remain with c
What is wrong in the code? Please help. Highly Appreciated
Upvotes: 1
Views: 2924
Reputation: 6538
There is nothing wrong with your add
method as shown by the following code:
public class Q21114229 {
public static void main(String[] args) {
DLList<Employee> l = new DLList<Employee>();
l.add(new Employee("a"));
l.add(new Employee("b"));
l.add(new Employee("c"));
System.out.println("Employee b test: " + l.getHead().getNext().getNext().getPrevious().get().getName());
}
static class Node<T> {
private Node<T> next;
private Node<T> previous;
private T value;
public Node(T value) { this.value = value; }
public T get() { return value; }
public Node<T> getNext() { return next; }
public void setNext(Node<T> next) { this.next = next; }
public Node<T> getPrevious() { return previous; }
public void setPrevious(Node<T> previous) { this.previous = previous; }
}
static class DLList<T> {
private Node<T> head;
private Node<T> tail;
public Node<T> getHead() { return head; }
public Node<T> getTail() { return tail; }
public boolean isEmpty() { return (head == null); }
public void add(T value) {
Node<T> n = new Node<T>(value);
if (isEmpty()) {
head = tail = n;
} else {
tail.setNext(n);
n.setPrevious(tail);
tail = n;
}
}
}
static class Employee {
private String name;
public Employee(String name) { this.name = name; }
public String getName() { return name; }
}
}
Output:
Employee b test: b
One of the other list-methods is not properly updating the Node's next/previous variables.
Upvotes: 0