这是我得到的代码。我必须添加代码的添加和删除方法。我已经尝试这样做了一段时间,但是我无法使其通过JUNIT测试。对此,我将不胜感激。祝你有美好的一天!(在第二个代码块中,我尝试添加方法)
包ss.ss.week4;
公共类DoublyLinkedList {
private int size;
private Node head;
/**
* @ensures the list is empty (size is 0)
*/
public DoublyLinkedList() {
size = 0;
head = new Node(null);
head.next = head;
head.previous = head;
}
/**
* Inserts a new Element at a given index in the list.
* @requires element is not null
* @requires the index to be within the bounds of the list
* @ensures the size of the list to increase by one
* @ensures the Element in the list at index index to be element
* @param index The index at which to insert the Element
* @param element The element to add
*/
public void add(int index, Element element) {
// TODO: implement, see exercise P-4.4
}
/**
* Removes an element at a given index
* @requires the index to be within the bounds of the list
* @ensures the size of the list to decrease by one
* @param index the index to remove the element at
*/
public void remove(int index) {
// TODO: implement, see exercise P-4.4
}
/**
* @requires the index to be within the bounds of the list
*/
public Element get(int index) {
Node p = getNode(index);
return p.element;
}
/**
* The node containing the element with the specified index.
* The head node if the specified index is -1.
* @requires i to be between -1 and the size of the list
*/
public Node getNode(int i) {
Node p = head;
int pos = -1;
while (pos < i) {
p = p.next;
pos = pos + 1;
}
return p;
}
public int size() {
return this.size;
}
public class Node {
public Node(Element element) {
this.element = element;
this.next = null;
this.previous = null;
}
private Element element;
public Node next;
public Node previous;
public Element getElement() {
return element;
}
}
}
Node newNode = new Node(element);
if (index == 0) {
DoublyLinkedList<Element>.Node first = null;
newNode.next = first;
first = newNode;
} else {
Node p = getNode(index - 1);
newNode= p.next;
p.next = newNode;
}
this.size++;